PHP设计模式之迭代器模式

迭代器模式(Iterator Pattern)

  • 迭代器模式在不需要了解内部实现的前提下,遍历一个聚合对象的内部元素
  • 相比于传统的编程模式,迭代器模式可以隐藏遍历元素的所需的操作
<?php
namespace IMooc;

class AllUser implements \Iterator
{
    protected $ids;
    protected $data = array();
    protected $index;

    function __construct()
    {
        $db = Factory::getDatabase();
        $result = $db->query("select id from user");
        $this->ids = $result->fetch_all(MYSQLI_ASSOC);
    }

    function current()
    {
        $id = $this->ids[$this->index]['id'];
        return Factory::getUser($id);
    }

    function next()
    {
        $this->index ++;
    }

    function valid()
    {
        return $this->index < count($this->ids);
    }

    function rewind()
    {
        $this->index = 0;
    }

    function key()
    {
        return $this->index;
    }

}

实现

$users = new \IMooc\AllUser();
foreach ($users as $user) {
    var_dump($user->name);
}

猜你喜欢

转载自blog.csdn.net/qq_36045946/article/details/81024149