In-depth analysis of PHP design pattern in iterator Pattern

Source: Internet
Author: User

The Iterator mode provides an abstraction in a common process: an iteration of a set of objects (or scalar) that are located in an unknown part of an object graph. Iterations have several different execution methods: iteration over an array attribute, set object, array, or even a query result set.

In the object world, the iterator mode needs to maintain functions similar to arrays. It is regarded as a non-invasive facet. The Client class is often separated from the real object implementation, which refers to the iterator interface. Whenever possible, we can send a reference to the iterator to replace the specific or abstract classes that may change in the future.

Participants:
◆ Client ):
A method that references the iterator mode executes a loop on a group of values or objects.
◆ Iterator ):Abstraction in the iteration process, including next (), isFinished (), current (), and other methods.
◆ Specific iterator (ConcreteIterators ):Implement iteration on a specific object set, such as an array, tree, combination, and set.
Through the Traversable interface, PHP originally supports the Iterator mode, which is extended by Iterator and IteratorAggregate. These two subinterfaces not only define a set of standard methods, each Traversable object can be passed to foreach () in an intact manner. foreach is the main client of the Iterator, Iterator implementation is the real Iterator, and IteratorAggregate is a Traversable object with other responsibilities, it returns an Iterator through the getIterator () method.

The standard PHP library is the only universal object-oriented library bound to PHP and defines additional interfaces and public classes. OuterIterator implements the decoration of an Iterator. CachingIterator and LimitIterator are two examples of this interface.

RecursiveIterator is an extension implemented by the Iterator interface for the tree structure. It defines a set of additional methods to check whether the Sub-objects of the current element in an iteration exist. RecursiveArrayIterator and RecursiveDirectoryIterator are implementation examples of this interface. These types of iterators can be used as they are, or a RecursiveIteratorIterator bridge is connected to a common iterator contract. This OuterIterator implements depth-first or breadth-first traversal based on the construction parameters.

When using RecursiveIteratorIterator, you can pass the recursiveiteratator to foreach. Please refer to the code examples below to learn about the different usage of RecursiveIterators and their superset Iterator. Finally, SeekableIterators adds a seek () method to the contract, which can be used to move the internal state of the Iterator to a specific iteration point.

Note:The Iterator is better abstract than the object set, because we can make InfiniteIterators, NoRewindIterators, and so on without having to be consistent with the ordinary array. Therefore, Iterator lacks functions such as the count () function.

You can find the complete SPL iterator list in the official PHP manual. Thanks to the strong support for PHP, most of the work using the Iterator mode is included in the standard implementation. The following code example uses the functions of the standard Iterator and RecursiveIterators.
Copy codeThe Code is as follows:
<? Php
/**
* Collection that wraps a numeric array.
* All five public methods are needed to implement
* The Iterator interface.
*/
Class Collection implements Iterator
{
Private $ _ content;
Private $ _ index = 0;

Public function _ construct (array $ content)
{
$ This-> _ content = $ content;
}

Public function rewind ()
{
$ This-> _ index = 0;
}

Public function valid ()
{
Return isset ($ this-> _ content [$ this-> _ index]);
}

Public function current ()
{
Return $ this-> _ content [$ this-> _ index];
}

Public function key ()
{
Return $ this-> _ index;
}

Public function next ()
{
$ This-> _ index ++;
}
}

$ Array = array ('A', 'B', 'C', 'D ');
Echo "Collection :";
Foreach (new Collection ($ array) as $ key => $ value ){
Echo "$ key => $ value .";
}
Echo "\ n ";
/**
* Usually IteratorAggregate is the interface to implement.
* It has only one method, which must return an Iterator
* Already defined as another class (e.g. ArrayIterator)
* Iterator gives a finer control over the algorithm,
* Because all the hook points of Iterator 'Contract
* Are available for implementation.
*/
Class NumbersSet implements IteratorAggregate
{
Private $ _ content;

Public function _ construct (array $ content)
{
$ This-> _ content = $ content;
}

Public function contains ($ number)
{
Return in_array ($ number, $ this-> _ content );
}

/**
* Only this method is necessary to implement IteratorAggregate.
* @ Return Iterator
*/
Public function getIterator ()
{
Return new ArrayIterator ($ this-> _ content );
}
}

Echo "NumbersSet :";
Foreach (new NumbersSet ($ array) as $ key => $ value ){
Echo "$ key => $ value .";
}
Echo "\ n ";
// Let's play with RecursiveIterator implementations
$ It = new RecursiveArrayIterator (array (
'A ',
'B ',
Array (
'C ',
'D'
),
Array (
Array (
'E ',
'F'
),
Array (
'G ',
'H ',
'I'
)
)
));
// $ It is a RecursiveIterator but also an Iterator,
// So it loops normally over the four elements
// Of the array.
Echo "Foreach over a RecursiveIterator :";
Foreach ($ it as $ value ){
Echo $ value;
// But RecursiveIterators specify additional
// Methods to perform e children nodes
$ Children = $ it-> hasChildren ()? '{Yes}': '{No }';
Echo $ children ,'';
}
Echo "\ n ";
// We can bridge it to a different contract
// A RecursiveIteratorIterator, whose cryptic name
// Shocould be read as an Iterator that spans over
// A RecursiveIterator '.
Echo "Foreach over a RecursiveIteratorIterator :";
Foreach (new RecursiveIteratorIterator ($ it) as $ value ){
Echo $ value;
}
Echo "\ n ";

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.