An in-depth analysis of the iterative mode of PHP design pattern _php Skills

Source: Internet
Author: User

Iterator (iterator) mode, which provides an abstraction on a common process: an iteration over a set of objects (or scalars) that are located in an unknown part of the object graph. There are several different ways to execute an iteration: Iterate over an array property, a collection object, an array, or even a query result set.

In the object world, the iterator pattern maintains an array-like function as a Non-intrusive object facet (facet), and the client class is often separated from the real object implementation, referring to the iterator interface. Whenever possible, we can send a reference to an iterator instead of a specific or abstract class that might change in the future.

Participants:
Client:
A method that references an iterator pattern executes a loop over a set of values or objects.
iterator (iterator): an abstraction over an iterative process, including next (), isfinished (), current (), and so on.
specific iterator (concreteiterators): implements iterations in a specific set of objects, such as arrays, trees, combinations, sets, etc.
Through the Traversable interface, PHP's original ecosystem supports the iterator pattern, which is extended by iterator and iteratoraggregate, and these two sub-interfaces are not only defined as a set of standard methods, Each Traversable object can be passed unaltered to foreach (), and foreach is the primary client of the iterator, and the iterator implementation is the true iterator, and Iteratoraggregate is the Traversable object with other responsibilities , it returns a iterator through the Getiterator () method.

The standard PHP Library is the only general-purpose object-oriented library that binds to PHP, defining additional interfaces and common classes. The Outeriterator implementation decorates a iterator,cachingiterator and Limititerator is the two examples of this interface.

Recursiveiterator is an extension of the iterator interface for the tree structure, which defines a set of additional methods to check for the existence of child objects of the current element in the iteration. Recursivearrayiterator and Recursivedirectoryiterator are examples of implementations of this interface, and these types of iterators can be used as is, Or a recursiveiteratoriterator bridge to a normal iterator contract. This outeriterator implementation will perform depth-first or breadth-first traversal based on the constructor parameters.

When using Recursiveiteratoriterator, you can pass it to foreach, looking at the following code examples to learn about the different uses 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 that an iterator is a better abstraction than an object set, because we can let infiniteiterators,norewinditerators, and so on, not be consistent with regular array arrays, so iterator lacks the count () function.

A complete list of SPL iterators can be found in the official PHP manual. Thanks to strong support for PHP, most of the work using the iterator pattern is included in the standard implementation, and the following code example leverages the capabilities of standard iterator and recursiveiterators.

Copy Code code 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 which must return a 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 it 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 a 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 explore children nodes
$children = $it->haschildren ()? ' {Yes} ': ' {No} ';
echo $children, ';
}
echo "\ n";
We can bridge it to a different contract via
A recursiveiteratoriterator, whose cryptic name
Should be read as ' a 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.