Rumah >pembangunan bahagian belakang >tutorial php >php设计模式之迭代器模式
1.概念介绍
1.迭代器模式:在不需要了解内部实现的前提下,遍历一个聚合对象的内部元素。
2.相比于传统的编程模式,迭代器模式可以隐藏遍历元素的所需的操作。
3.这里介绍的迭代器需要实现(implements)PHP SPL 里面的Iterator
,需要实现5个方法(current, next,valid,rewid,key)
2.代码展示
<code><span>namespace</span><span>brave</span><span>class</span><span>AllUser</span><span>implements</span> \<span>Iterator</span> { //所有<span>user</span>的<span>id</span><span>protected</span> $<span>ids</span>; <span>//保存数据库查询的对象,如果有就不需要在次查询了,可使用注册模式</span><span>protected</span><span>$data</span> = <span>array</span>(); <span>//表示迭代器当前的位置</span><span>protected</span><span>$index</span>; <span><span>function</span><span>__construct</span><span>()</span> {</span><span>$db</span> = Factory::getDatabase(); <span>$result</span> = <span>$db</span>->query(<span>"select id from user"</span>); <span>$this</span>->ids = <span>$result</span>->fetch_all(MYSQLI_ASSOC); } <span>//获取当前用户对象</span><span><span>function</span><span>current</span><span>()</span> {</span><span>$id</span> = <span>$this</span>->ids[<span>$this</span>->index][<span>'id'</span>]; <span>return</span> Factory::getUser(<span>$id</span>); } <span>//进入下一个索引</span><span><span>function</span><span>next</span><span>()</span> {</span><span>$this</span>->index ++; } <span>//检查当前是否有数据</span><span><span>function</span><span>valid</span><span>()</span> {</span><span>return</span><span>$this</span>->index $this->ids); } <span>//使当前的指针回到开始位置</span><span><span>function</span><span>rewind</span><span>()</span> {</span><span>$this</span>->index = <span>0</span>; } <span>//获取当前的索引值</span><span><span>function</span><span>key</span><span>()</span> {</span><span>return</span><span>$this</span>->index; } }</code>
3.执行代码
<code><span>//迭代器模式实例</span><span>$users</span> = <span>new</span> AllUser(); <span>foreach</span> (<span>$users</span><span>as</span><span>$user</span>) { var_dump(<span>$user</span>); <span>echo</span><span>'<hr>'</span>; }</code>
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了php设计模式之迭代器模式,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。