PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 13 ■ DATABASE PATTERNS

Collection object. While there’s nothing wrong with allowing callbacks (as you have seen in the Visitor
and Observer patterns,), it’s neater to move responsibility for domain object creation into its own type.
This can then be shared by Mapper and Collection classes alike.
The Domain Object Factory is described in Data Access Patterns.


Implementation


Imagine a set of Mapper classes, broadly organized so that each faces its own domain object. The Domain
Object Factory pattern simply requires that you extract the createObject() method from each Mapper
and place it in its own class in a parallel hierarchy. Figure 13–7 shows these new classes:


Figure 13–7. Domain Object Factory classes


Domain Object Factory classes have a single core responsibility, and as such, they tend to be simple:

namespace woo\mapper;
// ...


abstract class DomainObjectFactory {
abstract function createObject( array $array );
}


Here’s a concrete implementation:

namespace woo\mapper;
// ...
class VenueObjectFactory extends DomainObjectFactory {
function createObject( array $array ) {
$obj = new \woo\domain\Venue( $array['id'] );
$obj->setname( $array['name'] );
return $obj;
}
}


Of course, you might also want to cache objects to prevent duplication and prevent unnecessary
trips to the database as I did within the Mapper class. You could move the addToMap() and getFromMap()

Free download pdf