PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 13 ■ DATABASE PATTERNS

Here is an Iterator implementation that wraps an array but also accepts a Mapper object in its
constructor for reasons that will become apparent:


namespace woo\mapper;
//...


abstract class Collection implements \Iterator {
protected $mapper;
protected $total = 0;
protected $raw = array();


private $result;
private $pointer = 0;
private $objects = array();


function __construct( array $raw=null, Mapper $mapper=null ) {
if (! is_null( $raw ) &&! is_null( $mapper ) ) {
$this->raw = $raw;
$this->total = count( $raw );
}
$this->mapper = $mapper;
}


function add( \woo\domain\DomainObject $object ) {
$class = $this->targetClass();
if (! ($object instanceof $class ) ) {
throw new Exception("This is a {$class} collection");
}
$this->notifyAccess();
$this->objects[$this->total] = $object;
$this->total++;
}


abstract function targetClass();


protected function notifyAccess() {
// deliberately left blank!
}
private function getRow( $num ) {
$this->notifyAccess();
if ( $num >= $this->total || $num < 0 ) {
return null;
}
if ( isset( $this->objects[$num]) ) {
return $this->objects[$num];
}


if ( isset( $this->raw[$num] ) ) {
$this->objects[$num]=$this->mapper->createObject( $this->raw[$num] );
return $this->objects[$num];
}
}


public function rewind() {

Free download pdf