PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 13 ■ DATABASE PATTERNS

$query .= implode ( " = ?,", array_keys( $fields ) )." = ?";
$terms = array_values( $fields );
$cond = array();
$query .= " WHERE ";
foreach ( $conditions as $key=>$val ) {
$cond[]="$key = ?";
$terms[]=$val;
}
$query .= implode( " AND ", $cond );
} else {
$query = "INSERT INTO {$table} (";
$query .= implode( ",", array_keys($fields) );
$query .= ") VALUES (";
foreach ( $fields as $name => $value ) {
$terms[]=$value;
$qs[]='?';
}
$query .= implode( ",", $qs );
$query .= ")";
}
return array( $query, $terms );
}
}


In interface terms, the only thing that this class does is define the newUpdate() method. This will
return an array containing a query string, and a list of terms to apply to it. The buildStatement() method
does the generic work involved in building the update query, with the work specific to individual domain
objects handled by child classes. buildStatement() accepts a table name, an associative array of fields
and their values, and a similar associative array of conditions. The method combines these to create the
query. Here’s a concrete UpdateFactory class:


namespace woo\mapper;
//...


class VenueUpdateFactory extends UpdateFactory {


function newUpdate( \woo\domain\DomainObject $obj ) {
// not type checking removed
$id = $obj->getId();
$cond = null;
$values['name'] = $obj->getName();
if ( $id > -1 ) {
$cond['id'] = $id;
}
return $this->buildStatement( "venue", $values, $cond );
}
}


In this implementation, I work directly with a DomainObject. In systems where one might operate on
many objects at once in an update, I could use an identity object to define the set on which I would like
to act. This would form the basis of the $cond array, which here only holds id data.
newUpdate() distills the data required to generate a query. This is the process by which object data is
transformed to database information.

Free download pdf