PHPBuilder - PHP Iterator Page 5



RSS Twitter
Articles Application Architecture

PHP Iterator - Page 5

by: Dejan Bosanac
|
February 25, 2003

The third solution is to use an ObjectIterator class that is extended from Iterator. In this example we will see how easy it is to extend Iterator class to serve your purposes. When you are using ObjectIterator your getEmployee() function will stay the same as in second solution. So, we have saved our resources. No unnecessary objects are created and everything looks just fine. Now let's look at the usage code:

<?php
$company 
= new Company("Datagate");
$iterator = new Iterator($company->getEmployees(), "Employee");
while (
$employee $iterator->next()) {
    
$employee->addVacationDays(3);
}
?>
We see now that the object creation code is hidden in the ObjectIterator class, so it is now easy to support changes.

ObjectIterator implementation

The code for ObjectIterator is quite simple.

<?php
/**
 * Implements iterator for traversing collection of objects
 * for the given array od object identifiers
 * 
 * @version 1.0
 * @author <a href=mailto:chubrilo@yahoo.com>Dejan Bosanac</a>
 */
class ObjectIterator extends Iterator {

    var 
$_objectName;
    
    
/**
     * Constructor
     * Calls initialization method (@see Iterator::_initialize()) 
     * and do some specific configuration
     * @param array $array array of object ids to be traversed
     * @param string $objectName class of objects to be created
     * @access public
     */
    
function ObjectIterator($array$objectName) {
        
$this->_initialize($array);
        
$this->_objectName $objectName;
    }
    
    
/**
     * Returns object with given id
     * @param Object $id identifier of the object
     * @return Object next object in the collection
     * @access private
     */ 
    
function _fetchObject($id) {
        return new 
$this->_objectName($id);
    }
}
?>
It has $_objectName class member that represent class of the object that has to be returned by next() and previous() methods. The constructor sets this internal variable and calls an initialization function (defined in Iterator class). The most important thing is the _fetchObject() function. It encapsulates code for object creation. It is called from next() and previous() methods and takes object id as a parameter. So all your object creation code is localized here, thus making it easy to change and expand.

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Dejan Bosanac

Comment:



Comment:

(Maximum characters: 1200). You have characters left.