PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 13 ■ DATABASE PATTERNS

persistent storage. Magic is nice, but clarity is nicer. It may be better to require client code to pass some
kind of flag into the constructor in order to queue the new object for insertion.
I also need to add some code to the Mapper class:


// Mapper
function createObject( $array ) {
$old = $this->getFromMap( $array['id']);
if ( $old ) { return $old; }
$obj = $this->doCreateObject( $array );
$this->addToMap( $obj );
$obj->markClean();
return $obj;
}


Because setting up an object involves marking it new via the constructor’s call to
ObjectWatcher::addNew(), I must call markClean(), or every single object extracted from the database will
be saved at the end of the request, which is not what I want.
The only thing remaining to do is to add markDirty() invocations to methods in the Domain Model
classes. Remember, a dirty object is one that has been changed since it was retrieved from the database.
This is the one aspect of this pattern that has a slightly fishy odor. Clearly, it’s important to ensure that
all methods that mess up the state of an object are marked dirty, but the manual nature of this task
means that the possibility of human error is all too real.
Here are some methods in the Space object that call markDirty():


namespace woo\domain;


//...


class Space extends DomainObject {


//...


function setName( $name_s ) {
$this->name = $name_s;
$this->markDirty();
}


function setVenue( Venue $venue ) {
$this->venue = $venue;
$this->markDirty();
}


Here is some code for adding a new Venue and Space to the database, taken from a Command class:

$venue = new \woo\domain\Venue( null, "The Green Trees" );
$venue->addSpace(
new \woo\domain\Space( null, 'The Space Upstairs' ) );
$venue->addSpace(
new \woo\domain\Space( null, 'The Bar Stage' ) );


// this could be called from the controller or a helper class
\woo\domain\ObjectWatcher::instance()->performOperations();


I have added some debug code to the ObjectWatcher, so you can see what happens at the end of the
request:

Free download pdf