Iterator pattern

From Wikipedia, the free encyclopedia

In object-oriented programming, the Iterator pattern is a design pattern in which iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation. An Iterator object encapsulates the internal structure of how the iteration occurs.

For example, a tree, linked list, hash table, and an array all need to be iterated with Search, Sort, Next. Rather than having 12 different methods to manage, using this Pattern would allow you to only need to manage 7 methods.

Contents

[edit] Examples

[edit] PHP 5

As a default behavior in PHP 5, using an object in a foreach structure will traverse all public values. Multiple Iterator classes are available with PHP to allow you to iterate through common lists, such as directories, XML structures and recursive arrays.

It's possible to define your own Iterator classes by implementing the Iterator interface, which will override the default behavior.

The Iterator interface definition:

 interface Iterator
 {
   // Returns the current value
   function current();
   
   // Returns the current key
   function key();
   
   // Moves the internal pointer to the next element
   function next();
   
   // Moves the internal pointer to the first element
   function rewind();
   
   // If the current element is valid (boolean)
   function valid();
 }

These methods are all being used in a complete foreach( $object as $key=>$value ) sequence. The methods are executed in the following order:

 rewind() 
 if valid() {
   current() in $value 
   key() in $key 
   next()
 } 
 End of Loop 

According to Zend, the current() method is called before and after the valid() method

[edit] See also

[edit] External links