迭代器:类继承PHP的Iterator接口,批量操作。

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

namespace Lib;

class AllUser implements \Iterator
{
    protected $index = 0;

    private $data;

    public function __construct()
    {
        $db = Factory::getDb();
        $db->connect('127.0.0.1','root',123456,'demo');
        $result = $db->query("select id from user");
        $this->data = $result->fetch_all(MYSQLI_ASSOC);

        var_dump($this->data);
    }

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

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

    public function key(){
        return $this->index;
    }
    public function valid(){
        return $this->index < count($this->data);
    }

    public function rewind(){
        $this->index = 0;
    }
}
$users = new \Lib\AllUser();

foreach ($users as $user){
    print_r($user);
}

results matching ""

    No results matching ""

    results matching ""

      No results matching ""