PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 13 ■ DATABASE PATTERNS


$this->pointer = 0;
}


public function current() {
return $this->getRow( $this->pointer );
}


public function key() {
return $this->pointer;
}


public function next() {
$row = $this->getRow( $this->pointer );
if ( $row ) { $this->pointer++; }
return $row;
}


public function valid() {
return (! is_null( $this->current() ) );
}
}


The constructor expects to be called with no arguments or with two (the raw data that may
eventually be transformed into objects and a mapper reference).
Assuming that the client has set the $raw argument (it will be a Mapper object that does this), this is
stored in a property together with the size of the provided dataset. If raw data is provided an instance of
the Mapper is also required, since it’s this that will convert each row into an object.
If no arguments were passed to the constructor, the class starts out empty, though note that there is
the add() method for adding to the collection.
The class maintains two arrays: $objects and $raw. If a client requests a particular element, the
getRow() method looks first in $objects to see if it has one already instantiated. If so, that gets returned.
Otherwise, the method looks in $raw for the row data. $raw data is only present if a Mapper object is also
present, so the data for the relevant row can be passed to the Mapper::createObject() method you
encountered earlier. This returns a DomainObject object, which is cached in the $objects array with the
relevant index. The newly created DomainObject object is returned to the user.
The rest of the class is simple manipulation of the $pointer property and calls to getRow(). Apart,
that is, from the notifyAccess() method, which will become important when you encounter the Lazy
Load pattern.
You may have noticed that the Collection class is abstract. You need to provide specific
implementations for each domain class:


namespace woo\mapper;
//...


class VenueCollection
extends Collection
implements \woo\domain\VenueCollection {


function targetClass( ) {
return "\woo\domain\Venue";
}
}

Free download pdf