PHP迭代器模式
迭代器模式通俗的讲是遍历集合的成熟模式,迭代器模式的关键是将遍历集合的任务交给一个叫做迭代器的对象,它的工作时遍历并选择序列中的对象,而客户端程序员不必知道或关心该集合序列底层的结构。它的作用是使所有复杂数据结构的组件都可以使用循环来访问。
对象要实现迭代,需要使这个类实现 Iterator(SPL standard php library标准库提供),这是一个迭代器接口,实现该接口,必须实现以下方法:
1 2 3 4 5 6 |
current(),该函数返回当前数据项 key(),该函数返回当前数据项的键或者该项在列表中的位置 next(),该函数使数据项的键或者位置前移 rewind(),该函数重置键值或者位置 valid(),该函数返回 bool 值,表明当前键或者位置是否指向数据值 实现了 Iterator 接口和指定的方法后,PHP就知道此类型的对象需要迭代。 |
现在部门已经有两个成员了,现在我想把全部的成员都列出来,可以用循环来获取部门的每个员工的详情,这里我们用PHP中的SPL标准库提供的迭代器来实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
//部门类 class Department implements Iterator { private $_name; private $_employees; private $_position; //标志当前数组指针位置 function __construct($name) { $this->_name = $name; $this->employees = array(); $this->_position = 0; } function addEmployee(Employee $e) { $this->_employees[] = $e; echo "员工{$e->getName()}被分配到{$this->_name}中去"; } //实现 Iterator 接口要求实现的方法 function current() { return $this->_employees[$this->_position]; } function key() { return $this->_position; } function next() { $this->_position++; } function rewind() { $this->_position = 0; } function valid() { return isset($this->_employees[$this->_position]); } } //员工类 class Employee{ private $_name; function __construct($name){ $this->_name = $name; } function getName(){ return $this->_name; } } //应用: $lsgo = new Department('部门'); $e1 = new Employee("韩梅梅"); $e2 = new Employee("露西"); $lsgo->addEmployee($e1); $lsgo->addEmployee($e2); echo "部门成员情况:"; //这里其实遍历的$_employee foreach($lsgo as $val){ echo "部员{$val->getName()}"; } |
假如现在我们想要知道该部门有几个员工,如果是数组的话,一个 count() 函数就 ok 了,那么我们能不能像上面那样把对象当作数组来处理?SPL标准库中提供了 Countable 接口供我们使用:
1 2 3 4 5 6 7 8 9 10 11 |
class Department implements Iterator,Countable{ //前面同上 //实现Countable中要求实现的方法 function count(){ return count($this->_employees); } } echo "员工数量:"; echo count($lsgo); |
php中所有迭代器,可参考文档 http://www.ruanyifeng.com/blog/2008/07/php_spl_notes.html,写得不错哟