PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 13 ■ DATABASE PATTERNS


abstract class DomainObject {
private $id = -1;


function __construct( $id=null ) {
if ( is_null( $id ) ) {
$this->markNew();
} else {
$this->id = $id;
}
}


function markNew() {
ObjectWatcher::addNew( $this );
}


function markDeleted() {
ObjectWatcher::addDelete( $this );
}


function markDirty() {
ObjectWatcher::addDirty( $this );
}


function markClean() {
ObjectWatcher::addClean( $this );
}


function setId( $id ) {
$this->id = $id;
}


function getId( ) {
return $this->id;
}


function finder() {
return self::getFinder( get_class( $this ) );
}


static function getFinder( $type ) {
return HelperFactory::getFinder( $type );
}
//...


Before looking at the Unit of Work code, it is worth noting that the Domain class here has finder()
and getFinder() methods. These work in exactly the same way as collection() and getCollection(),
querying a simple factory class, HelperFactory, in order to acquire Mapper objects when needed. This
relationship was illustrated in Figure 13–3.
As you can see, the constructor method marks the current object as new (by calling markNew()) if no
$id property has been passed to it. This qualifies as magic of a sort and should be treated with some
caution. As it stands, this code slates a new object for insertion into the database without any
intervention from the object creator. Imagine a coder new to your team writing a throwaway script to
test some domain behavior. No sign of persistence code there, so all should be safe enough, shouldn’t it?
Now imagine these test objects, perhaps with interesting throwaway names, making their way into

Free download pdf