HomePHP Building a Data Access Layer for the Data Mapper Design Pattern
Building a Data Access Layer for the Data Mapper Design Pattern
In this second part of a five-part series I go one step further in the implementation of the Data Mapper design pattern in PHP 5. Specifically, I build a simple MySQL abstraction class which performs a few common tasks. These include connecting to the database server and running hard-coded queries, fetching database rows and so forth.
Put in a simple way, the Data Mapper design pattern is an elegant solution that allows developers to keep all of the domain objects handled by an application separate from the underlying persistence layer. This characteristic is commonly known as persistence ignorance. As with many other patterns, the implementation of data mappers either in PHP 5 or any other programming language isnít something that must be done all the time, as this depends heavily on the requirements of the application being developed.
Whatís more, in many cases using domain objects that are aware of the data access layer is a suitable approach; the use of Active Record is a good example. However, as soon as the structure of those objects doesnít match the database schema, the implementation of an intermediate layer that resolves this incompatibility internally is necessary. Here's where data mappers come into play, although there are other patterns, such as Data Access Objects, that also address this issue in an effective manner.
In order to demonstrate the actual functionality of data mappers when using PHP, in the introductory installment of this series I started building a simple domain layer, which was comprised of an abstract class whose interfaced was used for modeling basic domain objects. Essentially, this class was a basic data container that implemented some magic PHP methods for adding and deleting object properties dynamically.
Based upon the interface and functionality encapsulated by this abstract class, it was possible to create concrete user objects easily via simple inheritance. With a domain layer already set, whatís the next step we must take in the implementation of data mappers? Well, as I said before, data mappers behave like "gluing elements" between domain objects and the data access layer. Thus, in this second tutorial Iím going to show you how to implement this layer. For the sake of brevity, it will be made up of a trivial MySQL abstraction class.
Want to learn the full details concerning the implementation of this sample data access layer? Then start reading now!