PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 13 ■ DATABASE PATTERNS


match, as it generates data transfer objects, but since such objects are designed to become the real thing
if you add water, the patterns are close enough).
As you might imagine, a data mapper is a class that is responsible for handling the transition from
database to object.


The Problem


Objects are not organized like tables in a relational database. As you know, database tables are grids
made up of rows and columns. One row may relate to another in a different (or even the same) table by
means of a foreign key. Objects, on the other hand, tend to relate to one another more organically. One
object may contain another, and different data structures will organize the same objects in different
ways, combining and recombining objects in new relationships at runtime. Relational databases are
optimized to manage large amounts of tabular data, whereas classes and objects encapsulate smaller
focussed chunks of information.
This disconnect between classes and relational databases is often described as the object-relational
impedance mismatch (or simply impedance mismatch).
So how do you make that transition? One answer is to give a class (or a set of classes) responsibility
for just that problem, effectively hiding the database from the domain model and managing the
inevitable rough edges of the translation.


Implementation


Although with careful programming, it may be possible to create a single Mapper class to service multiple
objects, it is common to see an individual Mapper for a major class in the Domain Model.
Figure 13–1 shows three concrete Mapper classes and an abstract superclass.


Figure 13–1. Mapper classes

Free download pdf