PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 13 ■ DATABASE PATTERNS


}


return $this->statements[$str];
}


function findOne( IdentityObject $idobj ) {
$collection = $this->find( $idobj );
return $collection->next();
}


function find( IdentityObject $idobj ) {
$selfact = $this->factory->getSelectionFactory( );
list ( $selection, $values ) = $selfact->newSelection( $idobj );
$stmt = $this->getStatement( $selection );
$stmt->execute( $values );
$raw = $stmt->fetchAll();
return $this->factory->getCollection( $raw );
}


function insert( \woo\domain\DomainObject $obj ) {
$upfact = $this->factory->getUpdateFactory( );
list( $update, $values ) = $upfact->newUpdate( $obj );
$stmt = $this->getStatement( $update );
$stmt->execute( $values );
if ( $obj->getId() < 0 ) {
$obj->setId( self::$PDO->lastInsertId() );
}
$obj->markClean();
}
}


As you can see, this is not an abstract class. Instead of itself breaking down into specializations, it
uses the PersistenceFactory to ensure that it gets the correct components for the current domain object.
Figure 13–11 shows the high-level participants I built up as I factored out Mapper.
Aside from making the database connection and performing queries, the class manages
SelectionFactory and UpdateFactory objects. In the case of selections, it also works either with a
Collection class or directly with a DomainObjectFactory to generate return values.
From a client’s point of view, acquiring a DomainObjectFactory is easy. It’s simply a matter of getting
the correct concrete PersistenceFactory object:


$factory = \woo\mapper\PersistenceFactory::getFactory("woo\domain\Venue" );
$finder = new \woo\mapper\DomainObjectAssembler( $factory );


Although, of course, it would be even easier to add a getFinder() method to the PersistenceFactory
itself and transform the previous example into a one-liner like this:


$finder = \woo\mapper\PersistenceFactory::getFinder( 'woo\domain\Venue' );


I’ll leave that to you, however.
Free download pdf