PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 13 ■ DATABASE PATTERNS

The VenueCollection class simply extends Collection and implements a targetClass() method.
This, in conjunction with the type checking in the super class’s add() method, ensures that only Venue
objects can be added to the collection. You could provide additional checking in the constructor as well
if you wanted to be even safer.
Clearly, this class should only work with a VenueMapper. In practical terms, though, this is a
reasonably type-safe collection, especially as far as the Domain Model is concerned.
There are parallel classes for Event and Space objects, of course.
Note that VenueCollection implements an interface: woo\domain\VenueCollection. This is part of the
Separated Interface trick I will describe shortly. In effect, it allows the domain package to define its
requirements for a Collection independently of the mapper package. Domain objects hint for
woo\domain\VenueCollection objects and not woo\mapper\VenueCollection objects, so that, at a later
date, the mapper implementation might be removed. It could then be replaced with an entirely different
implementing class without many changes within the domain package.
Here is the \woo\domain\VenueCollection interface, together with its siblings.


namespace woo\domain;


interface VenueCollection extends \Iterator {
function add( DomainObject $venue );
}


interface SpaceCollection extends \Iterator {
function add( DomainObject $space );
}


interface EventCollection extends \Iterator {
function add( DomainObject $event );
}


Figure 13–2 shows some Collection classes.

Figure 13–2. Managing multiple rows with collections

Free download pdf