PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 13 ■ DATABASE PATTERNS

$self->new = array_filter( $self->new,
function( $a ) use ( $obj ) { return !( $a === $obj ); }
);
}


function performOperations() {
foreach ( $this->dirty as $key=>$obj ) {
$obj->finder()->update( $obj );
}
foreach ( $this->new as $key=>$obj ) {
$obj->finder()->insert( $obj );
}
$this->dirty = array();
$this->new = array();
}


The ObjectWatcher class remains an Identity Map and continues to serve its function of tracking all
objects in a system via the $all property. This example simply adds more functionality to the class.
You can see the Unit of Work aspects of the ObjectWatcher class in Figure 13–6.


Figure 13–6. Unit of Work


Objects are described as “dirty” when they have been changed since extraction from the database. A
dirty object is stored in the $dirty array property (via the addDirty() method) until the time comes to
update the database. Client code may decide that a dirty object should not undergo update for its own
reasons. It can ensure this by marking the dirty object as clean (via the addClean() method). As you
might expect, a newly created object should be added to the $new array (via the addNew() method).
Objects in this array are scheduled for insertion into the database. I am not implementing delete
functionality in these examples, but the principle should be clear enough.
The addDirty() and addNew() methods each add an object to their respective array properties.
addClean(), however, removes the given object from the $dirty array, marking it as no longer pending
update.
When the time finally comes to process all objects stored in these arrays, the performOperations()
method should be invoked (probably from the controller class, or its helper). This method loops through
the $dirty and $new arrays either updating or adding the objects.
The ObjectWatcher class now provides a mechanism for updating and inserting objects. The code is
still missing a means of adding objects to the ObjectWatcher object.
Since it is these objects that are operated upon, they are probably best placed to perform this
notification. Here are some utility methods I can add to the DomainObject class. Notice also the
constructor method.


// DomainObject
namespace woo\domain;
//...

Free download pdf