PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 13 ■ DATABASE PATTERNS

The EventIdentityObject class now enforces a set of fields. Here’s what happens if I try to work with
a random field name:


PHP Fatal error: Uncaught exception 'Exception' with message 'banana not a ➥
legal field (name, id, start, duration, space)'...


Consequences


Identity objects allow client coders to define search criteria without reference to a database query. They
also save you from having to build special query methods for the various kinds of find operation your
user might need.
Part of the point of an identity object is to shield users from the details of the database. It’s
important, therefore, that if you build an automated solution like the fluent interface in the preceding
example, the labels you use should refer explicitly to your domain objects and not to the underlying
column names. Where these differ, you should construct a mechanism for aliasing between them.
Where you use specialized entity objects, one for each domain object, it is useful to use an abstract
factory (like PersistenceFactory described in the previous section) to serve them up along with other
domain object related objects.
Now that I can represent search criteria, I can use this to build the query itself.


The Selection Factory and Update Factory Patterns


I have already pried a few responsibilities from the Mapper classes. With these patterns in place a Mapper
does not need to create objects or collections. With query criteria handled by Identity Objects, it must no
longer manage multiple variations on the find() method. The next stage is to remove responsibility for
query creation.


The Problem


Any system that speaks to a database must generate queries, but the system itself is organized around
domain objects and business rules rather than the database. Many of the patterns in this chapter can be
said to bridge the gap between the tabular database and the more organic, treelike structures of the
domain. There is, however, a moment of translation—the point at which domain data is transformed
into a form that a database can understand. It is at this point that the true decoupling takes place.


Implementation


Of course, you have seen some of this functionality before in the Data Mapper pattern. In this
specialization, though, I can benefit from the additional functionality afforded by the identity object
pattern. This will tend to make query generation more dynamic, simply because the potential number of
variations is so high.
Figure 13–10 shows my simple selection and update factories.

Free download pdf