迭代器:类继承PHP的Iterator操作,批量操作
1 迭代器模式 在不需要了解内部实现的前提下,遍历一个聚合对象的内部元素
2 相比传统的变成模式,迭代器模式可以隐藏遍历元素的所需操作
3 允许对象以自己的方式迭代内部的数据,从而使它可以被循环访问
接口Iterator
- Iterator extends Traversable {
- //返回当前索引游标指向的元素
- abstract public mixed current ( void )
- //返回当前索引游标指向的键
- abstract public scalar key ( void )
- //移动当前索引游标到下一元素
- abstract public void next ( void )
- //重置索引游标
- abstract public void rewind ( void )
- //判断当前索引游标指向的元素是否有效
- abstract public boolean valid ( void )
- }
<?php /** * Created by PhpStorm. * User: wangkai * Date: 2018/3/16 * Time: 上午9:29 */ class TestIterator implements Iterator { /* * 定义要进行迭代的数组 */ private $_test = array('dog', 'cat', 'pig'); /* * 索引游标 */ private $_key = 0; /* * 执行步骤 */ private $_step = 0; /** * 将索引游标指向初始位置 * * @see TestIterator::rewind() */ public function rewind() { echo '第'.++$this->_step.'步:执行 '.__METHOD__.'<br>'; $this->_key = 0; } /** * 判断当前索引游标指向的元素是否设置 * * @see TestIterator::valid() * @return bool */ public function valid() { echo '第'.++$this->_step.'步:执行 '.__METHOD__.'<br>'; return isset($this->_test[$this->_key]); } /** * 将当前索引指向下一位置 * * @see TestIterator::next() */ public function next() { echo '第'.++$this->_step.'步:执行 '.__METHOD__.'<br>'; $this->_key++; } /** * 返回当前索引游标指向的元素的值 * * @see TestIterator::current() * @return value */ public function current() { echo '第'.++$this->_step.'步:执行 '.__METHOD__.'<br>'; return $this->_test[$this->_key]; } /** * 返回当前索引值 * * @return key * @see TestIterator::key() */ public function key() { echo '第'.++$this->_step.'步:执行 '.__METHOD__.'<br>'; return $this->_key; } } $iterator = new TestIterator(); foreach($iterator as $key => $value){ echo "输出索引为{$key}的元素".":$value".'<br><br>'; } ?>
另一个例子:数据表对象
class AllUser implements \Iterator { protected $index = 0; protected $data = []; public function __construct() { $link = mysqli_connect('192.168.0.91', 'root', '123', 'xxx'); $rec = mysqli_query($link, 'select id from doc_admin'); $this->data = mysqli_fetch_all($rec, MYSQLI_ASSOC); } //1 重置迭代器 public function rewind() { $this->index = 0; } xxx //2 验证迭代器是否有数据 public function valid() { return $this->index < count($this->data); } //3 获取当前内容 public function current() { $id = $this->data[$this->index]; return User::find($id); } //4 移动key到下一个 public function next() { return $this->index++; } //5 迭代器位置key public function key() { return $this->index; } } //实现迭代遍历用户表 $users = new AllUser(); //可实时修改 foreach ($users as $user){ $user->add_time = time(); $user->save(); }