Bleaaaah. I haven't revisited or updated this issue in a long time. I'm still of the mind this is a good way to loop over results. jk 2007
The PHP Patterns wiki is locked, so these notes are being written here. The URL to the Iterator Pattern is:
http://www.phppatterns.com/docs/design/the_iterator_pattern
See the linked article for the discussion about the SimpleIterator.
The typical use case in PHP is that the iterator loops over a result from an SQL query, and the objects returned are database rows (as arrays). The traditional Iterator pattern can return any type of object, including hierarchies of objects, or objects of different classes.
A different kind of iterator pattern should be used for PHP. I'll call it the ViewIterator for now. Unlike the traditional iterator, $this->next() doesn't return the next object. Instead, it returns the boolean true, until it's at the end of the list, when it returns false. next() also sets the properties of the object to the next row. The typical code to use a ViewIterator looks like this:
while( $obj->next() )
{
echo $obj->propA;
echo $obj->propB;
}
The ViewIterator avoids the creation of an object, saving memory and time.
The ViewIterator can be used to encapsulate iterations over delimited text files, arrays, file directories, files, and other collections. The main limitation is that it cannot iterate over a collection of mixed object types or mixed data types. For example, it's somewhat unwiedly to iterate over a directory full of files and other directories, even if there's a property that indicates the type. It's probably better to create a separate ViewIterator for each type.
The ViewIterator lacks a previous() method. PHP doesn't commonly require code to move backwards over a list.
The ViewIterator interface is: next(); rewind();
The idea of the ViewIterator was based on work by Josh from Slaptech.