PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 13 ■ DATABASE PATTERNS


Notice that the newUpdate() method will accept any DomainObject. This is so that all UpdateFactory
classes can share an interface. It would be a good idea to add some further type checking to ensure the
wrong object is not passed in.
You can see a similar structure for SelectionFactory classes. Here is the base class:


namespace woo\mapper;


//...


abstract class SelectionFactory {
abstract function newSelection( IdentityObject $obj );


function buildWhere( IdentityObject $obj ) {
if ( $obj->isVoid() ) {
return array( "", array() );
}
$compstrings = array();
$values = array();
foreach ( $obj->getComps() as $comp ) {
$compstrings[] = "{$comp['name']} {$comp['operator']} ?";
$values[] = $comp['value'];
}
$where = "WHERE ". implode( " AND ", $compstrings );
return array( $where, $values );
}
}


Once again, this class defines the public interface in the form of an abstract class. newSelection()
expects an IdentityObject. Also requiring an IdentityObject but local to the type is the utility method
buildWhere(). This uses the IdentityObject::getComps() method to acquire the information necessary
to build a WHERE clause, and to construct a list of values, both of which it returns in a two element array.
Here is a concrete SelectionFactory class:


namespace woo\mapper;


//...


class VenueSelectionFactory extends SelectionFactory {


function newSelection( IdentityObject $obj ) {
$fields = implode( ',', $obj->getObjectFields() );
$core = "SELECT $fields FROM venue";
list( $where, $values ) = $this->buildWhere( $obj );
return array( $core." ".$where, $values );
}
}


This builds the core of the SQL statement and then calls buildWhere() to add the conditional clause.
In fact, the only thing that differs from one concrete SelectionFactory to another in my test code is the
name of the table. If I don’t find that I require unique specializations soon, I will refactor these
subclasses out of existence and use a single concrete SelectionFactory. This would query the table name
from the PersistenceFactory.

Free download pdf