HomePHP Building the Data Mapper Classes for the Data Mapper Design Pattern
Building the Data Mapper Classes for the Data Mapper Design Pattern
In this third part of a five-part series on the data mapper design pattern, I start developing a basic user mapper class. This class allows you to map user domain objects to their associated database table in a fairly easy way.
The Data Mapper design pattern is a powerful and elegant solution that permits developers to isolate domain objects from the underlying persistence storage mechanism of an application. Its implementation, at least at a basic level, is a pretty straightforward process that can be tackled with minor hassles.
In the case of PHP, building data mapper classes can be a challenging task, especially for developers who are taking their first steps into the huge area of design patterns. Once the logic that drives data mappers has been properly digested, however, their implementation is indeed fairly simple.
Naturally, explaining how to create one or more data mapper classes requires the performance of some initialization tasks, such as defining a few domain objects that make up the domain layer and implementing a data access layer (DAL).
In keeping with this requirement, these two layers were developed in the preceding parts of this series. For demonstration purposes, the domain objects were created as simple data containers, capable of adding and removing properties dynamically, while the data access layer was comprised only of a single MySQL abstraction class.
The fact that these layers currently live isolated from each other sets a propitious scenario for taking advantage of the data mapper patternís functionality. The question that comes up here is: why should the pattern be implemented, anyway? Well, if the structure of the domain objects matches the structure of the database tables in a one-to-one relationship, the problem is far easier to solve, quite possibly by using an Active Record implementation.
Unfortunately, in most cases this match doesnít occur. Consider, for instance, a basic domain layer comprised of blog post objects that also have an associated author object. In a case like this, storing blog posts will require working with two different tables, instead of only one. However, the good news is that this incompatibility can be resolved by means of a data mapper, without making the domain objects aware of the persistence layer.
Having said that, in this third part of the series Iíll be discussing how to create some basic data mapper classes, which will bridge the pair of layers defined in the previous chapters. Now, to find out how this will be achieved, go ahead and start reading!