Home arrow PHP arrow Page 3 - External Iterators in PHP Using OOP

Defining the Functionality of PHP Array Iterators - PHP

In this first part of a short tutorial series, you will learn how to implement external iterators in PHP using OOP (Object Oriented Programming). This is useful when you want to construct easily traversable classes. Keep reading to learn more!

  1. External Iterators in PHP Using OOP
  2. Creating the External Iterator in PHP
  3. Defining the Functionality of PHP Array Iterators
By: Alejandro Gervasio
Rating: starstarstarstarstar / 4
March 21, 2011

print this article



Finally, to demonstrate the actual functionality of this external iterator, it’s necessary to derivate a subclass from the parent “EntityAbstract”. To keep things clear and easy to grasp, I’m going to reuse the previous “User” class, whose implementation remains exactly the same. Check it out:



namespace Model;

class User extends EntityAbstract
    protected $_allowedFields = array('_id', '_name' , '_email');
    protected $_id;
    protected $_name;
    protected $_email;  
     * Set the user's ID
    public function setId($id)
        if(!filter_var($id, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 65535)))) {
            throw new \OutOfRangeException('The supplied ID ' . $id . ' is invalid.');
        $this->_id = $id;
     * Set the user's name
    public function setName($name)
        if (strlen($name) < 2 || strlen($name) > 32) {
            throw new \OutOfRangeException('The supplied name ' . $name . ' is invalid.');
        $this->_name = $name;
     * Set the user's email address
    public function setEmail($email)
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \OutOfRangeException('The supplied email address ' . $email . ' is invalid.');
        $this->_email = $email;

So far, so good. At this point, I proved that building an external iterator (in this case a simple array wrapper) in PHP is actually much easier to accomplish than one might think. The question that probably keeps your mind spinning in circles is if it’s possible to traverse any child spawned from the parent “EntityAbstract” using the previous array collection.

Actually, the answer to that question is a resounding yes! But, to dissipate your eventual doubts, in the coming section I’m going to create an example that will demonstrate how to achieve this with the earlier “User” class.

To see how this example will be developed, go ahead and keep reading.

Putting the external iterator to work: setting up a final example

Remember the script that I wrote at the beginning to test the “EntityAbstract” class when it made use of an ugly inner iterator? Well, the good news is that it’s possible to reutilize it for trying out the improved version of the class. In case that you’re skeptical about my words, take a peek at the following code fragment:


use Model\User as User;

// include the autoloader
require_once 'Autoloader.php';

// create a user object
$user = new User(array(
    '_id'    => 1,
    '_name'  => 'Sandra Wilson',
    '_email' => 'sandra@domain.com'

// count the number of fields of the user
echo 'The number of fields of the user is ' . count($user) . '.<br />';

/* displays the following
The number of fields of the user is 3.

// iterate over the user and display their value/field pairs
foreach ($user as $field => $value) {
    echo "The value assigned to the field '$field' is $value.<br />";

/* displays the following
The value assigned to the field '_id' is 1.
The value assigned to the field '_name' is Sandra Wilson.
The value assigned to the field '_email' is sandra@domain.com.

There you have it. From a client code’s standpoint, any subclass derived from “EntityAbstract” is really traversable, something demonstrated above with the familiar “User” class. In this case, however, things are done more efficient behind the scenes, as the whole iteration process has been delegated to the outer “ArrayCollection” iterator.

Of course, you might argue that it’s possible to produce a similar result by calling directly the class’ “toArray()” method, and certainly you’d be right. However, having a class that transparently gets an outer iterator when used in a “foreach” loop can be very powerful, specially when it comes to lazy-loading data from the storage layer. But, in fact I’m getting ahead of myself, since this topic will be covered in detail in a forthcoming installment of this series. So, in the interim feel free to stop by the article’s final thoughts.  

Final thoughts

In this first chapter of the series, I introduced you to implementing external iterators in PHP. As you saw for yourself, in most cases the development of this kind of structures relies on the use of the IteratorAggregate SPL interface; so if you’re not familiar with the inner workings of this native interface, I suggest you to take a look at its documentation here (http://www.php.net/manual/en/class.iteratoraggregate.php).

In addition, it’s valid to stress that in the prior example I used a custom outer iterator to traverse the protected members of any entity derived from the abstract “AbstractEntity” class. While this approach worked decently well, it’s feasible to utilize the built-in ArrayIterator PHP class and achieve similar results.

In line with this idea, in the coming tutorial I’m going to amend the source code of the aforementioned “AbstractEntity” class, which this time will employ the native ArrayIterator to traverse concrete entities spawned from it.

Don’t miss the next part!      


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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- 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: