PHP
  Home arrow PHP arrow Page 2 - The Iterator Pattern, concluded
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

The Iterator Pattern, concluded
By: php|architect
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 5
    2005-12-01


    Table of Contents:
  • The Iterator Pattern, concluded
  • Sorting Iterator
  • SPL Iterator
  • Issues

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    The Iterator Pattern, concluded - Sorting Iterator
    ( Page 2 of 4 )

    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
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek