HomePHP Implementing the Data Mapper Design Pattern in PHP 5
Implementing the Data Mapper Design Pattern in PHP 5
In this first part of a five-part series, I introduce you to implementing the Data Mapper design pattern in PHP 5. This pattern attempts to solve the issue of the strong coupling that often exists between the domain objects present in an application and the underlying persistence mechanism. This benefit comes at a cost, since data mappers add a new layer of complexity. Living with this minor trade-off is quite worthwhile, though, as you'll see.
Since the web is in constant evolution and merges a variety of technologies and languages, developing web applications (specially mid-sized and large-scale ones) has become a challenging process. Indeed, applications require extensive planning, modeling and testing, before reaching a stable deployment stage.
In the case of PHP, different solutions and tools have emerged in the last few years, aimed at making the development process as painless as possible. These include a large number of MVC-driven frameworks, which, when coupled with well-trusted libraries, allow developers to build complex web programs without having to write code from scratch.
Without a doubt, using a framework that implements an MVC layer will help in developing applications that separate business and application logic from the visual presentation. In many cases developers will start setting up the persistent storage mechanism, usually composed of some relational tables; then they'll define the model classes that will manage those tables; and finally they'll code the controllers and views respectively. In short, what could be faster, more effective and simpler than this strategy?
Well, for a small application tightly coupled to a specific framework, and even worse, to a predefined persistence mechanism, this approach will work fairly well. However, what happens if the application suddenly needs to be modified to persist using a web service or a bunch of XML files? All of those beautifully-crafted, database-dependent models will cry, and loudly, trust me. Usually, models encapsulate multiple domain objects, such as users, blog posts and comments, but this doesn't necessarily mean that they must always maintain their state through the same persistence layer. Are you getting the big picture here?
Fortunately, there are a few design patterns that permit you to fairly easily decouple domain objects from the underlying persistent mechanism (a characteristic known as persistence ignorance or PI). Data Mapper is one of the most popular. Data Access Objects (DAO) are also used with similar purposes in many cases, but as this article's title suggests, in the lines to come I'm going to discuss how to implement only the former.
Now that you have at least a vague idea of the goal for using the Data Mapper pattern, it's time to show how to implement it in PHP 5. So, go ahead and start reading. A lot of code is waiting for us!