迭代器模式
- 迭代器模式,在不需要了解内部实现的情况下,遍历一个聚合对象的内部元素。
- 相对于传统的编程模式,迭代器模式可以隐藏遍历元素所需要的操作。
示例代码:
<?php
namespace TT;
class AllUser implements \Iterator
{
protected $ids;
protected $index;
protected $data = [];
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 count($this->ids) > $this->index;
}
// 第一步:重置
function rewind()
{
$this->index = 0;
}
// 获取当前索引
function key()
{
return $this->index;
}
}
<?php
$users = new \TT\AllUser();
foreach($users as $user)
{
var_dump($user->name);
}
总结
迭代器的类继承一个php标准类库的迭代器接口Iterator,里面一共包含了5个方法。只要实现了这5个方法,就可以在最外面进行foreach循环,就可以获取到对应的数据。
上一页 下一页