PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 13 ■ DATABASE PATTERNS

}


class EventIdentityObject
extends IdentityObject {
private $start = null;
private $minstart = null;


function setMinimumStart( $minstart ) {
$this->minstart = $minstart;
}


function getMinimumStart() {
return $this->minstart;
}


function setStart( $start ) {
$this->start = $start;
}


function getStart() {
return $this->start;
}
}


Nothing’s too taxing here. The classes simply store the data provided and give it up on request.
Here’s some code that might use SpaceIdentityObject to build a WHERE clause:


$idobj = new EventIdentityObject();
$idobj->setMinimumStart( time() );
$idobj->setName( "A Fine Show" );
$comps = array();
$name = $idobj->getName();
if (! is_null( $name ) ) {
$comps[] = "name = '{$name}'";
}
$minstart = $idobj->getMinimumStart();
if (! is_null( $minstart ) ) {
$comps[] = "start > {$minstart}";
}


$start = $idobj->getStart();
if (! is_null( $start ) ) {
$comps[] = "start = '{$start}'";
}


$clause = " WHERE ". implode( " and ", $comps );


This model will work well enough, but it does not suit my lazy soul. For a large domain object, the
sheer number of getters and setters you would have to build is daunting. Then, following this model,
you’d have to write code to output each condition in the WHERE clause. I couldn’t even be bothered to
handle all cases in my example code (no setMaximumStart() method for me), so imagine my joy at
building identity objects in the real world.
Luckily, there are various strategies you can deploy to automate both the gathering of data and the
generation of SQL. In the past, for example, I have populated associative arrays of field names in the
base class. These were themselves indexed by comparison types: greater than, equal, less than or equal

Free download pdf