PHP Design Pattern iterator mode

Source: Internet
Author: User
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.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.