PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 13 ■ DATABASE PATTERNS


to. The child classes provide convenience methods for adding this data to the underlying structure. The
SQL builder can then loop through the structure to build its query dynamically. I’m sure implementing
such a system is just a matter of coloring in, so I’m going to look at a variation on it here.
I will use a fluent interface. That is a class whose setter methods return object instances, allowing
your users to chain objects together in fluid, language-like way. This will satisfy my laziness, but still, I
hope, give the client coder a flexible way of defining criteria.
I start by creating woo\mapper\Field, a class designed to hold comparison data for each field that will
end up in the WHERE clause:


namespace woo\mapper;


class Field {
protected $name=null;
protected $operator=null;
protected $comps=array();
protected $incomplete=false;


// sets up the field name (age, for example)
function __construct( $name ) {
$this->name = $name;
}


// add the operator and the value for the test
// (> 40, for example) and add to the $comps property
function addTest( $operator, $value ) {
$this->comps[] = array( 'name' => $this->name,
'operator' => $operator, 'value' => $value );
}


// comps is an array so that we can test one field in more than one way
function getComps() { return $this->comps; }


// if $comps does not contain elements, then we have
// comparison data and this field is not ready to be used in
// a query
function isIncomplete() { return empty( $this->comps); }
}


This simple class accepts and stores a field name. Through the addTest() method the class builds an
array of operator and value elements. This allows us to maintain more than one comparison test for a
single field. Now, here’s the new IdentityObject class:


namespace woo\mapper;


class IdentityObject {
protected $currentfield=null;
protected $fields = array();
private $and=null;
private $enforce=array();


// an identity object can start off empty, or with a field
function __construct( $field=null, array $enforce=null ) {
if (! is_null( $enforce ) ) {
$this->enforce = $enforce;
}

Free download pdf