Home arrow PHP arrow Page 2 - The Iterator Pattern, concluded

Sorting Iterator - PHP

This article, the second of two parts, explains how to use the Iterator pattern to manipulate any collection of objects. It is excerpted from chapter eight of the book PHP|architect's Guide to PHP Design Patterns, written by Jason E. Sweat (PHP|architect, 2005; ISBN: 0973589825).

TABLE OF CONTENTS:
  1. The Iterator Pattern, concluded
  2. Sorting Iterator
  3. SPL Iterator
  4. Issues
By: php|architect
Rating: starstarstarstarstar / 5
December 01, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

An iterator can do more than show all or a portion of the collection. An iterator can also show the collection in a specific order. Let's create an iterator that sorts the Media in the collection by release date.

For a test, add some Media instances with dates older that those of the items added in the setUp() method. If the iterator works, these older items should be sorted to the beginning of the iteration.

  class IteratorTestCase extends UnitTestCase {
   
// ...
    
function TestReleasedIteratorUsage() {
     
$this->lib->add(new Media('second', 1999));
     
$this->lib->add(new Media('first', 1989));
     
$this->assertIsA(
        
$it = $this->lib->getIterator('released')
        ,'LibraryReleasedIterator');
     
$output = array();
     
while ($item = $it->next()) {
       
$output[] = $item->name .'-'.  $item->year;
     
}
     
$this->assertEqual(
        '
first-1989 second-1999 name1-2000 name3-2001 name2-2002'
        ,implode('',$output));
   
}
 
}

This test uses the items in each iteration slightly differently: instead of just appending the $name values in a string, a string is formed from both the $name and $year properties, which is then appended to an $output array.

The implementation of LibraryReleasedIterator is nearly identical to LibraryIterator, except for one additional line in the constuctor:

  class LibraryReleasedIterator extends LibraryIterator {
   
function __construct($collection) {
     
usort($collection, create_function('$a,$b','return ($a->year - $b->year);'));
     
$this->collection = $collection;
   
}
 
}

The line in bold sorts the $collection array prior to iteration. You can avoid copying all of the other code for the class by simply inheriting from the LibraryIterator class itself.

Is it possible to use an external iterator to accomplish this same sorted iteration? Yes, but you must pull a few tricks to accomplish it.

  class LibraryReleasedExternalIterator {
   
protected $collection;
   
protected $sorted_keys;
   
protected $key=-1;
   
function __construct($collection) {
     
$this->collection = $collection;
     
$sort_funct = create_function(
        '
$a,$b,$c=false',
        '
static $collection;
       
if ($c) {
         
$collection = $c;
         
return;
       
}
       
return ($collection->get($a)->year -

          $collection->get($b)->year);');
     
$sort_funct(null,null,$this->collection);
     
$this->sorted_keys = $this->collection->keys();
     
usort($this->sorted_keys, $sort_funct);
    
}
   
function next() {
     
if (++$this->key >= $this->collection->count()) {
       
return false;
     
} else {
       
return $this->collection->get($this->sorted_keys[$this->key]);
     
}
   
}
 
}

Key here is the creation of a utility function for performing the sort. The sorting function needs to have access to the collection so it can fetch members for comparison. However, because the generated function is used in ausort(), you don't have the option of passing the collection as an additional parameter. Instead, you can use the trick shown in the code block above to store a reference to the collection inside the function prior to calling it with usort().

What you're sorting is the list of keys for the collection. When usort() is complete, the keys will be sorted in order by the year attribute of each object in the collection.

In the next() method, an object in the collection is accessed via the get() method, but indirectly through the $sorted_keys mapping. If you recall the external version of the GoF-style iterator, arrays with gaps or strings in the keys could be problematic. This same trick could be used for a simple external iterator to alleviate the problem of gaps in the sequence of keys.



 
 
>>> More PHP Articles          >>> More By php|architect
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: