php设计模式之迭代器模式

1.概念介绍

1.迭代器模式:在不需要了解内部实现的前提下,遍历一个聚合对象的内部元素。
2.相比于传统的编程模式,迭代器模式可以隐藏遍历元素的所需的操作。
3.这里介绍的迭代器需要实现(implements)PHP SPL 里面的Iterator,需要实现5个方法(current, next,valid,rewid,key)

2.代码展示

namespace brave

class AllUser implements \Iterator
{
    //所有userid
    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;
    }

}

3.执行代码

//迭代器模式实例
$users = new AllUser();
foreach ($users as $user) {
    var_dump($user);
    echo '<hr>';
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值