PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 13 ■ DATABASE PATTERNS


// namespace woo\mapper;
// ...


protected function doCreateObject( array $array ) {
$obj = new w\woo\domain\Venue( $array['id'] );
$obj->setname( $array['name'] );
$space_mapper = new SpaceMapper();
$space_collection = $space_mapper->findByVenue( $array['id'] );
$obj->setSpaces( $space_collection );
return $obj;
}


The VenueMapper::doCreateObject() method gets a SpaceMapper and acquires a SpaceCollection
from it. As you can see, the SpaceMapper class implements a findByVenue() method. This brings us to the
queries that generate multiple objects. For the sake of brevity, I omitted the Mapper::findAll() method
from the original listing for woo\mapper\Mapper. Here it is restored:


//Mapper
// namespace woo\mapper;
// ...


function findAll( ) {
$this->selectAllStmt()->execute( array() );
return $this->getCollection(
$this->selectAllStmt()->fetchAll( PDO::FETCH_ASSOC ) );
}


This method calls a child method: selectAllStmt(). Like selectStmt(), this should contain a
prepared statement object primed to acquire all rows in the table. Here’s the PDOStatement object as
created in the SpaceMapper class:


// SpaceMapper::__construct()
$this->selectAllStmt = self::$PDO->prepare(
"SELECT FROM space");
//...
$this->findByVenueStmt = self::$PDO->prepare(
"SELECT
FROM space where venue=?");


I included another statement here, $findByVenueStmt, which is used to locate Space objects specific
to an individual Venue.
The findAll() method calls another new method, getCollection(), passing it its found data. Here is
SpaceMapper::getCollection():


function getCollection( array $raw ) {
return new SpaceCollection( $raw, $this );
}


A full version of the Mapper class should declare getCollection() and selectAllStmt() as abstract
methods, so all mappers are capable of returning a collection containing their persistent domain
objects. In order to get the Space objects that belong to a Venue, however, I need a more limited
collection. You have already seen the prepared statement for acquiring the data; now, here is the
SpaceMapper::findByVenue() method, which generates the collection:


function findByVenue( $vid ) {
$this->findByVenueStmt->execute( array( $vid ) );
return new SpaceCollection(

Free download pdf