PHP
  Home arrow PHP arrow Page 2 - Iterators in the Simplest Sense: Trave...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Moblin 
JMSL Numerical Library 
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? 
PHP

Iterators in the Simplest Sense: Traversing Data Structures in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 6
    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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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


       · This last tutorial of the series shows how to apply the Iterator pattern in PHP 5,...
       · The idea is great! I couldn't get it to work, however. Seems like the problem lies...
       · Thank you for reading and commenting on this PHP article. With reference to the...
     

       

    PHP ARTICLES

    - Validating Web Forms with the Code Igniter P...
    - Output Buffering
    - Paginating Database Records with the Code Ig...
    - HTTP Headers in Web Development
    - Project Management: Administration
    - Building a Database-Driven Application with ...
    - User Authentication for a Project Management...
    - Introduction to the CodeIgniter PHP Framework
    - Adding Users for a Project Management Applic...
    - Migrating Class Code for a MIME Email to PHP...
    - Login and Logout Authentication for a Projec...
    - Composing Messages in HTML for MIME Email wi...
    - Project Management: Authentication
    - A Better Way to Determine MIME Types for MIM...
    - Project Management Overview





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway