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 < count(<span>$this</span>->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教學有興趣的朋友有幫助。