PHP
  Home arrow PHP arrow Page 2 - Iterators in the Simplest Sense: Traversing Data Structures in PHP 5
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

Iterators in the Simplest Sense: Traversing Data Structures in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 7
    2006-03-22


    Table of Contents:
  • Iterators in the Simplest Sense: Traversing Data Structures in PHP 5
  • Working with iterators in PHP 5: using some predefined SPL classes
  • Traversing text files the easy way: the brand new FileIterator class
  • Traversing database result sets: building a MySQL iterator class

  • 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


    Iterators in the Simplest Sense: Traversing Data Structures in PHP 5 - Working with iterators in PHP 5: using some predefined SPL classes
    ( Page 2 of 4 )

    When PHP 5 was initially released, it included a strong sense of standardization introduced in the core package. This can be a real time saver when common programming issues must be solved through proven, standard solutions. That's precisely the case with iterators, since the SPL package includes many predefined iterating classes that can be used for traversing different data structures, without having to reinvent the wheel over and over again.

    In this particular case, in order to illustrate how data of a distinct type can be accessed by the same set of methods, what I'll do next is use the "ArrayObject" class, included within the SPL package, to construct some comprehensive iterators in PHP 5. Of course, here there's plenty of room to experiment with other predefined classes, such as "ArrayIterator" or "DirectoryIterator," among others, so if you're interested in learning more on the subject, take a look at the PHP manual. In my opinion it's the best resource for further reading.

    Now, after a short theoretical introduction to iterators in PHP 5, it's time to illustrate a simple process for building a file iterator class, similar to the one I showed in my second article. The definition for this class is shown below:

    class FileIterator {
        private $iterator;
        public function __construct($file){
            if(!file_exists($file)){
                throw new Exception('Invalid input file');
            }
            // get ArrayObject
            $arrayobj=new ArrayObject();
            // get Iterator object
            $this->iterator=$arrayobj->getIterator();
            $lines=file($file);
            foreach($lines as $line){
                $arrayobj[]=$line;
            }
        }
        // get first line of file
        public function rewind(){
            return $this->iterator->rewind();
        }
        // get current line of file
        public function current(){
            if($this->iterator->valid()){
                return $this->iterator->current();
            }
        }
        // get next line of file
        public function next(){
            if($this->iterator->valid()){
                return $this->iterator->next();
            }
        }
        public function seek($pos){
            if(!is_int($pos)||$pos<0){
                throw new Exception('Invalid position');
            }
            return $this->iterator->seek($pos);
        }
        public function count(){
            return $this->iterator->count();
        }
    }

    If you study the above "FileIterator" class, you'll probably see that its source code is really easy to follow. As you've seen, this class exposes the most usual methods for traversing any data structure, such as the respective "rewind()," "current()" and "next()" methods. Even when this may seem like a trivial thing, please take a look at the signature for the corresponding class constructor, which is listed below:

    public function __construct($file){
        if(!file_exists($file)){
            throw new Exception('Invalid input file');
        }
        // get ArrayObject
        $arrayobj=new ArrayObject();
        // get Iterator object
        $this->iterator=$arrayobj->getIterator();
        $lines=file($file);
        foreach($lines as $line){
            $arrayobj[]=$line;
        }
    }

    As you can see in the above snippet, the constructor accepts the text file for being traversed as the only input parameter of the class. Now here's where things get really interesting: notice how this method first uses an instance of the predefined "ArrayObject" class, that is "$arrayobj,", then invokes the "getIterator()" method, and finally adds each line of the input file as new elements of the mentioned array.

    After storing the contents of the text file as elements of the "ArrayObject," traversing its structure is reduced to calling each of its methods, as indicated a few lines above. That's it. Don't tell me that wasn't really simple!

    Fine, at this point you know how to create a simple "FileIterator" class in PHP 5, which can be used as a building block for more sophisticated PHP applications. Now, the next step consists of illustrating with a simple example how this iterator class should be used for traversing a specific text file. Therefore, join me in the next section to find out how this process is performed.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    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