An in-depth analysis of the iterator pattern of PHP Design Patterns _php Tutorial

Source: Internet
Author: User
Iterator (Iterator) mode, which provides an abstraction on a very common process: an iteration on a set of objects (or scalars) in an unknown part of an object graph. Iterations have several different methods of execution: Iterating over Array properties, collection objects, arrays, or even a query result set.

In the world of objects, 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 on a set of values or objects.
iterator (Iterator): an abstraction in the iterative process, including methods such as Next (), isfinished (), current ().
specific iterators (concreteiterators): implement iterations on a specific set of objects, such as arrays, trees, combinations, collections, and so on.
With the Traversable interface, the PHP primitive supports the iterator pattern, which is extended by iterator and iteratoraggregate, which not only defines a standard set of methods, but also the two sub-interfaces. Each Traversable object can be passed intact to foreach (), which is the primary client of the iterator, the iterator implementation is a true iterator, and Iteratoraggregate is a traversable object with other responsibilities , which returns a iterator through the Getiterator () method.

The standard PHP Library is the only common purpose object-oriented library bound in PHP that defines additional interfaces and common classes. Outeriterator implementation decoration A iterator,cachingiterator and limititerator are two examples of this interface.

Recursiveiterator is an extension of the iterator interface to a tree structure that defines an additional set of 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 common iterator contract. This outeriterator implementation will perform a depth-first or breadth-first traversal based on the construction parameters.

When using Recursiveiteratoriterator, you can pass it to foreach, see the following code examples for different uses of recursiveiterators and their superset iterator. Finally, Seekableiterators adds a seek () method to the contract that can be used to move the internal state of the iterator to a specific iteration point.

Note that iterators are a better abstraction than object sets, because we can let infiniteiterators,norewinditerators and so on, without being consistent with ordinary array arrays, so iterator lacks functions such as the count () function.

A complete list of SPL iterators can be found in the official PHP manual. Thanks to strong support for PHP, much of the work using the iterator pattern is included in the standard implementation, and the following code example takes advantage of the functionality of standard iterator and recursiveiterators.
Copy CodeThe code is as follows:
/**
* Collection that wraps a numeric array.
* All five public methods is 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
* is 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 through 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";

http://www.bkjia.com/PHPjc/327554.html www.bkjia.com true http://www.bkjia.com/PHPjc/327554.html techarticle iterator (Iterator) mode, which provides an abstraction on a very common process: an iteration on a set of objects (or scalars) in an unknown part of an object graph. There are several types of iterations ...

  • Related Article

    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.