The third solution is to use an
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
have saved our resources. No unnecessary objects are created and
everything looks just fine. Now let’s look at the usage code:
ObjectIterator
class that is extended fromIterator. 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, wehave 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
class, so it is now easy to support changes.
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:[email protected]>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
to be returned by
internal variable and calls an initialization function (defined in Iterator class). The most important thing is the
$_objectName
class member that represent class of the object that hasto be returned by
next()
and previous()
methods. The constructor sets thisinternal 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.