PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 13 ■ DATABASE PATTERNS

Figure 13–3. Using a factory object as an intermediary to acquire persistence tools


// Venue
// namespace woo\domain;
// ...


function setSpaces( SpaceCollection $spaces ) {
$this->spaces = $spaces;
}


function getSpaces() {
if (! isset( $this->spaces ) ) {
$this->spaces = self::getCollection("woo\domain\Space");
}
return $this->spaces;
}


function addSpace( wSpace $space ) {
$this->getSpaces()->add( $space );
$space->setVenue( $this );
}


The setSpaces() operation is really designed to be used by the VenueMapper class in constructing the
Venue. It takes it on trust that all Space objects in the collection refer to the current Venue. It would be
easy enough to add checking to the method. This version keeps things simple though. Notice that I only
instantiate the $spaces property when getSpaces() is called. Later on, I’ll demonstrate how you can
extend this lazy instantiation to limit database requests.
The VenueMapper needs to set up a SpaceCollection for each Venue object it creates.


// VenueMapper

Free download pdf