迭代器模式为聚合对象的元素提供一种顺序访问的方式,又能让访问者不必关心聚合对象内部的内部实现。实际上我们平常使用最多的数组foreach操作就是在使用迭代器(注意:迭代器并不等于迭代器模式)。从php 5.3开始,php开始内置了iterator接口,为我们实现迭
迭代器模式为聚合对象的元素提供一种顺序访问的方式,又能让访问者不必关心聚合对象内部的内部实现。实际上我们平常使用最多的数组foreach操作就是在使用迭代器(注意:迭代器并不等于迭代器模式)。从php 5.3开始,php开始内置了iterator接口,为我们实现迭代器模式提供了便利:
//php5提供的iterator接口,traversable接口只是为了标识对象是否可以通过foreach迭代,不包含任何方法iterator extends traversable { /* methods */ 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来说,数组本身就是支持迭代的,我们为什么还要通过迭代器模式多封装一层呢?这就是模式定义的核心所在了:让访问者不必关心聚合对象的内部实现(比如元素数量、key、具体结构等);相对来说就是让聚合对象的内部实现不暴露给访问者(例如避免对象被访问者修改)。
实现我们自己的迭代器:
class recorditerator implements iterator{ private $position = 0; //注意:被迭代对象属性是私有的 private $records = array(); public function __construct(array $records) { $this->position = 0; $this->records = $records; } function rewind() { $this->position = 0; } function current() { return $this->records[$this->position]; } function key() { return $this->position; } function next() { ++$this->position; } function valid() { return isset($this->records[$this->position]); }}//假如我们从mongodb中读取得到下列数据$data = array( 0 => array('field' => 'value'), 1 => array('field' => 'value'), 2 => array('field' => 'value'), 3 => array('field' => 'value'),);//使用我们自己定义的迭代器$records = new recorditerator($data);while($records->valid()){ print_r($records->current()); $records->next();}$records->rewind();
在gof定义的迭代器模式中,还有两个参与者:容器和具体容器,负责初始化并返回具体的迭代器。
//容器interface aggregate{ public getiterator();}//具体容器class recordlist implements aggregate{ private $iterator; public function __construct($data){ $this->iterator = new recorditerator($data); } public function getiterator(){ return $this->iterator; }}//使用//假如我们从mongodb中读取得到下列数据$data = array( 0 => array('field' => 'value'), 1 => array('field' => 'value'), 2 => array('field' => 'value'), 3 => array('field' => 'value'),);$recordlist = new recordlist($data);$iterator = $recordlist->getiterator();while($iterator->valid()){ print_r($iterator->current()); $iterator->next();}