Iterator Design Pattern

The Iterator design pattern is used to elegantly retrieve the members of a collection. In PHP 5, that means implementing the Iterator interface defined in the Standard PHP Library (SPL).

In the Istarel Workshop Application Framework, two of the foundation classes are IWArray and IWDictionary, both of which are subclasses of the abstract class IWIterator. It is IWIterator that implements the Iterator interface.

Partial Listing: /fw/IWIterator.php

abstract class IWIterator implements Iterator
   protected $array = array();


   // methods required for the Iterator interface
   function current() { return current($this->array); }
   function next()    { return next($this->array);    }
   function key()     { return key($this->array);     }
   function valid()   { return current($this->array); }
   function rewind()  { return reset($this->array);   }


Now, any time I work with either an IWArray or IWDictionary object, I can use a foreach statement to iterate across the elements in the collection.

Pseudo Listing: /adhoc/iterator.php

// Retrieve data in the form of an array
$select = new ORMSelect('category');
$categories = ORMFactory::instanceArray('category');  // returns an IWArray object

foreach ($categories as $category)
   // do something interesting