As mentioned in the introduction, the implementation of the Data Mapper design pattern allows you to isolate all of the domain objects present in an application from the persistence mechanism in a pretty elegant and efficient way. Naturally, this brief description is somewhat obscure and abstract, so to shed some light, here's a contrived example that shows how to use a data mapper to perform CRUD operations on some persistence-ignorant user domain objects. The example in question is as follows:
// get instance of MySQL adapter class
$db = MySQL::getInstance();
// create instance of 'UserMapper' class
$userMapper = new UserMapper($db);
// get existing user by ID
$user = $userMapper->find(1);
// display user data
echo 'ID: '. $user->id . '<br />First Name: ' . $user->fname . '<br />Last Name: ' . $user->lname . '<br />Email: ' . $user->email;
// create a new user and add her to the database
$user = new User();
$user->fname = 'Sandra';
$user->lname = 'Smith';
$user->email = 'firstname.lastname@example.org';
// update existing user
$user = $userMapper->find(2);
$user->fname = 'Sandy';
// delete existing user
The above code sample shows how to use an instance of data mapper class to perform CRUD operations on a couple of user objects. As you can see, the data mapper is aware of the storage mechanism, which in this case happens to be a simple MySQL database, but the domain objects are completely ignorant of it. In consequence, it's the responsibility of the data mapper to execute the pertinent database operations, a process that not only permits decoupling the domain objects from the persistence layer, but makes those objects much easier to test and maintain.
Of course, this is only an introductory example that hides all of the complexities of the Data Mapper pattern behind a clean interface. My plan for this series, though, is to build a complete example from scratch that covers the development of the domain object classes, along with the associated data mappers, so get ready to read a lot of code samples. You've been warned!
At this point, you should have a more appropriate idea of the advantages to using the Data Mapper design pattern specifically in PHP 5, so it's time to start defining the sample classes required to implement it in a useful way. With that idea in mind, in the following segment I'm going to build the first of these classes, which will define the generic structure and behavior of the domain objects.
To learn how this initial class will be defined, click on the link below and read the next few lines.
blog comments powered by Disqus