Home arrow PHP arrow Page 2 - Iterators in the Simplest Sense: Traversing Data Structures in PHP 5

Working with iterators in PHP 5: using some predefined SPL classes - PHP

Welcome to the final part of the series “Iterators in the Simplest Sense.” In this set of articles, you’ll learn the basic concepts of iterators in PHP 4 and PHP 5. The overall learning experience is strongly focused on the practical sense of the topic, so you can start quickly using iterators within your own PHP applications.

TABLE OF CONTENTS:
  1. Iterators in the Simplest Sense: Traversing Data Structures in PHP 5
  2. Working with iterators in PHP 5: using some predefined SPL classes
  3. Traversing text files the easy way: the brand new FileIterator class
  4. Traversing database result sets: building a MySQL iterator class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 8
March 22, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

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: