1. Concept Introduction
1. Iterator mode: Iterates through the inner elements of an aggregated object without needing to know the internal implementation.
2. In contrast to traditional programming patterns, the iterator pattern can hide the required operations for traversing elements.
3. The iterator introduced here needs to implement (implements) PHP SPL inside Iterator , need to implement 5 methods (current, Next,valid,rewid,key)
2. Code display
namespaceBraveclassAllUserImplements\Iterator{//AllUserOfIDprotected$IDs;//Save the Database query object, if there is no need in the second query, you can use the registration modeprotected$data=Array();//Represents the current position of the iteratorprotected$index; function__construct() {$db= Factory::getdatabase ();$result=$db->query ("SELECT id from user");$this->ids =$result->fetch_all (MYSQLI_ASSOC); }//Get current User Object functioncurrent() {$id=$this->ids[$this->index][' id '];returnFactory::getuser ($id); }//Enter the next index functionnext() {$this->index + +; }//Check whether there is currently data functionvalid() {return$this->index < Count ($this->ids); }//Bring the current pointer back to the start position functionrewind() {$this->index =0; }//Gets the current index value functionkey() {return$this->index; }}
3. Execute code
//迭代器模式实例$usersnew AllUser();foreach ($usersas$user) { var_dump($user); echo'';}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The above describes the PHP design pattern of the iterator mode, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.