Integrating Data Mappers

Share this article

While there’s still a huge number of cases where Domain Models are considered an overkill “enterprisey” solution that doesn’t jive with the natural pragmatism that proliferates throughout the world of PHP, they’re steadily breaching the minds of many developers, even of those who cling to the Database Model paradigm like the last life jacket of a sinking ship.

There are some reasons that largely justify such a reaction. After all, building even the simplest Domain Model demands definition of the constraints, rules, and relationships among its building objects, how they will behave in a given context, and what type of data they’ll carry during their life cycle. Plus, the process of transferring model data to and from the storage will likely require to drop a set of Data Mappers at some point, a fact that highlights why Domain Models are often surrounded by a cloud of bullying.

Eager prejudgements tend to be misleading, though. The bones of a rich Domain Model will certainly be accommodated more comfortably inside the boundaries of a large application, but it’s possible to scale them down and get the most from them in smaller environments too. To demonstrate this, in my previous article I showed you how to implement a simple blog domain model composed of a few posts, comments, and user objects.

The previous article lacked a true happy ending; it merely showed the mechanics of the model, not how to put it to work in synchrony with a “real” persistence layer. So before you throw me to the lions for such an impolite attitude, in this follow-up we’ll be developing a basic mapping module which will allow you to move data easily between the blog’s model and a MySQL database, all while keeping them neatly isolated from one other.

Building a Naive DAL (or why my PDO adapter is better than yours)

The phrase may sound like an cheap cliché, I know, but I’m not particularly interested in reinventing the wheel each time I tackle a software problem (unless I need a nicer and faster wheel, of course). In this case, the situation does warrant some additional effort considering we’ll be trying to connect a batch of mapping classes to a blog’s domain model. Given the magnitude of the endeavor, the idea is to set up from scratch a basic Data Access Layer (DAL) so that domain objects can easily be persisted in a MySQL database, and in turn, retrieved on request through some generic finders.

The DAL in question will be made up of just a couple of components: the first one will be a simple database adapter interface, whose contract looks like this:

<?php
namespace LibraryDatabase;

interface DatabaseAdapterInterface
{
    public function connect();
    public function disconnect();
    
    public function prepare($sql, array $options = array());
    public function execute(array $parameters = array());
    
    public function fetch($fetchStyle = null, 
        $cursorOrientation = null, $cursorOffset = null);
    public function fetchAll($fetchStyle = null, $column = 0);
    
    public function select($table, array $bind, 
        $boolOperator = "AND");
    public function insert($table, array $bind);
    public function update($table, array $bind, $where = "");
    public function delete($table, $where = "");
}

Undeniably, the above DatabaseAdapterInterface is a tameable creature. Its contract allows us to create different database adapters at runtime and perform a few common tasks, such as connecting to the database and running CRUD operations without much fuss.

Now we need at least one implementer of the interface that does all these cool things. The proud cavalier that will assume this responsibility will be a non-canonical PDO adapter, which looks as follows:

<?php
namespace LibraryDatabase;

class PdoAdapter implements DatabaseAdapterInterface
{
    protected $config = array();
    protected $connection;
    protected $statement;
    protected $fetchMode = PDO::FETCH_ASSOC;   
    
    public function __construct($dsn, $username = null,
        $password = null, array $driverOptions = array()) {
        $this->config = compact("dsn", "username", "password", 
            "driverOptions");
    }

    public function getStatement() {
        if ($this->statement === null) {
            throw new PDOException(
              "There is no PDOStatement object for use.");
        } 
        return $this->statement;
    }
    
    public function connect() {
        // if there is a PDO object already, return early
        if ($this->connection) {
            return;
        }
 
        try {
            $this->connection = new PDO(
                $this->config["dsn"],
                $this->config["username"],
                $this->config["password"],
                $this->config["driverOptions"]);
            $this->connection->setAttribute(PDO::ATTR_ERRMODE,
                PDO::ERRMODE_EXCEPTION);
            $this->connection->setAttribute(
                PDO::ATTR_EMULATE_PREPARES, false); 
        }
        catch (PDOException $e) {
            throw new RunTimeException($e->getMessage());
        }
    }
    
    public function disconnect() {
        $this->connection = null;
    }
    
    public function prepare($sql, array $options = array() {
        $this->connect();
        try {
            $this->statement = $this->connection->prepare($sql, 
                $options);
            return $this;
        }
        catch (PDOException $e) {
            throw new RunTimeException($e->getMessage());
        }
    }
    
    public function execute(array $parameters = array()) {
        try {
            $this->getStatement()->execute($parameters);
            return $this;
        }
        catch (PDOException $e) {
            throw new RunTimeException($e->getMessage());
        }
    }
    
    public function countAffectedRows() {
        try {
            return $this->getStatement()->rowCount();
        }
        catch (PDOException $e) {
            throw new RunTimeException($e->getMessage());
        }
    }

    public function getLastInsertId($name = null) {
        $this->connect();
        return $this->connection->lastInsertId($name);
    }
    
    public function fetch($fetchStyle = null,
        $cursorOrientation = null, $cursorOffset = null) {
        if ($fetchStyle === null) {
            $fetchStyle = $this->fetchMode;
        }
 
        try {
            return $this->getStatement()->fetch($fetchStyle, 
                $cursorOrientation, $cursorOffset);
        }
        catch (PDOException $e) {
            throw new RunTimeException($e->getMessage());
        }
    }
     
    public function fetchAll($fetchStyle = null, $column = 0) {
        if ($fetchStyle === null) {
            $fetchStyle = $this->fetchMode;
        }
 
        try {
            return $fetchStyle === PDO::FETCH_COLUMN
               ? $this->getStatement()->fetchAll($fetchStyle, $column)
               : $this->getStatement()->fetchAll($fetchStyle);
        }
        catch (PDOException $e) {
            throw new RunTimeException($e->getMessage());
        }
    }
    
    public function select($table, array $bind = array(), 
        $boolOperator = "AND") {
        if ($bind) {
            $where = array();
            foreach ($bind as $col => $value) {
                unset($bind[$col]);
                $bind[":" . $col] = $value;
                $where[] = $col . " = :" . $col;
            }
        }
 
        $sql = "SELECT * FROM " . $table
            . (($bind) ? " WHERE "
            . implode(" " . $boolOperator . " ", $where) : " ");
        $this->prepare($sql)
            ->execute($bind);
        return $this;
    }
    
    public function insert($table, array $bind) {
        $cols = implode(", ", array_keys($bind));
        $values = implode(", :", array_keys($bind));
        foreach ($bind as $col => $value) {
            unset($bind[$col]);
            $bind[":" . $col] = $value;
        }
 
        $sql = "INSERT INTO " . $table
            . " (" . $cols . ")  VALUES (:" . $values . ")";
        return (int) $this->prepare($sql)
            ->execute($bind)
            ->getLastInsertId();
    }
    
    public function update($table, array $bind, $where = "") {
        $set = array();
        foreach ($bind as $col => $value) {
            unset($bind[$col]);
            $bind[":" . $col] = $value;
            $set[] = $col . " = :" . $col;
        }
 
        $sql = "UPDATE " . $table . " SET " . implode(", ", $set)
            . (($where) ? " WHERE " . $where : " ");
        return $this->prepare($sql)
            ->execute($bind)
            ->countAffectedRows();
    }
    
    public function delete($table, $where = "") {
        $sql = "DELETE FROM " . $table . (($where) ? " WHERE " . $where : " ");
        return $this->prepare($sql)
            ->execute()
            ->countAffectedRows();
    }
}

Feel free to curse me for throwing such a fat code snippet at you, but it was a necessary evil. What’s more, even while the PdoAdapter class looks somewhat tangled, it’s actually a simple wrapper which exploits much of the functionality that PDO offers right out the box without exposing client code to a verbose API.

Now that PdoAdapter is doing the dirty database work for us, let’s create a few MySQL tables which will store the data corresponding to blog posts, comments, and users:

CREATE TABLE posts (
  id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  title VARCHAR(100) DEFAULT NULL,
  content TEXT,

  PRIMARY KEY (id)
);

CREATE TABLE users (
  id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(45) DEFAULT NULL,
  email VARCHAR(45) DEFAULT NULL,

  PRIMARY KEY (id)
);

CREATE TABLE comments (
  id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  content TEXT,
  user_id INTEGER DEFAULT NULL,
  post_id INTEGER DEFAULT NULL,

  PRIMARY KEY (id),
  FOREIGN KEY (user_id) REFERENCES users(id),
  FOREGIN KEY (post_id) REFERENCES posts(id)
);

The above database schema defines a one-to-many relationship between posts and comments, and a one-to-one relationship between comments and users (the blog’s commentators). If you’re feeling adventurous, you’re free to tweak the schema at will to suit your specific needs. For the sake of brevity, however, I’ve kept it that simple.

At this point we’ve implemented a simple DAL which we can use for persisting the blog’s domain model in MySQL without sweating too much during the process. Now we need to add the middle men to the picture, that is the aforementioned data mappers, so any impedance mismatches can be handled quietly behind the scenes.

Implementing a Bi-directional Mapping Layer

It depends on the context of course, but most of the time building a mapping layer (and specifically a bi-directional relational one) is quite a ways away from being trivial. The process doesn’t boil down to just say… hey, I’ll get these relational mappers up and running during a coffee break. That’s why ORM libraries like Doctrine live and breathe after all. In this case, however, we want to leverage the bold coder living inside of us and create our own set of mappers to l massage the blog’s domain objects without facing the learning curve of a third-party package.

Let’s begin with encapsulating as much mapping logic as possible within an abstract class, like the below one:

<?php
namespace ModelMapper;
use LibraryDatabaseDatabaseAdapterInterface;

abstract class AbstractDataMapper
{
    protected $adapter;
    protected $entityTable;

    public function __construct(DatabaseAdapterInterface $adapter) {
        $this->adapter = $adapter;
    }

    public function getAdapter() {
        return $this->adapter;
    }

    public function findById($id)
    {
        $this->adapter->select($this->entityTable,
            array('id' => $id));

        if (!$row = $this->adapter->fetch()) {
            return null;
        }

        return $this->createEntity($row);
    }

    public function findAll(array $conditions = array())
    {
        $entities = array();
        $this->adapter->select($this->entityTable, $conditions);
        $rows = $this->adapter->fetchAll();

        if ($rows) {
            foreach ($rows as $row) {
                $entities[] = $this->createEntity($row);
            }
        }

        return $entities;
    }

    // Create an entity (implementation delegated to concrete mappers)
    abstract protected function createEntity(array $row);
}

The class abstracts away behind a couple of generic finders all of the logic required for pulling in data from a specified table, which is then used for reconstituting domain objects in a valid state. Because reconstitutions should be delegated down the hierarchy to refined implementations, the createEntity() method has been declared abstract.

Let’s now define the set of concrete mappers that will deal with blog posts, comments, and users. Here’s the first one, along with the interface it implements:

<?php
namespace ModelMapper;
use ModelPostInterface;

interface PostMapperInterface
{
   public function findById($id);
   public function findAll(array $conditions = array());

   public function insert(PostInterface $post);
   public function delete($id);
}
<?php
namespace ModelMapper;
use LibraryDatabaseDatabaseAdapterInterface,
    ModelPostInterface,
    ModelPost;

class PostMapper extends AbstractDataMapper implements PostMapperInterface
{
    protected $commentMapper;
    protected $entityTable = "posts";

    public function __construct(DatabaseAdapterInterface $adapter,
        CommentMapperInterface $commenMapper) {
        $this->commentMapper = $commenMapper;
        parent::__construct($adapter);
    }

    public function insert(PostInterface $post) {
        $post->id = $this->adapter->insert($this->entityTable,
            array("title"   => $post->title,
                  "content" => $post->content));
        return $post->id;
    }

    public function delete($id) {
        if ($id instanceof PostInterface) {
            $id = $id->id;
        }

        $this->adapter->delete($this->entityTable, "id = $id");
        return $this->commentMapper->delete("post_id = $id");
    }

    protected function createEntity(array $row) {
        $comments = $this->commentMapper->findAll(
            array("post_id" => $row["id"]));
        return new Post($row["title"], $row["content"], $comments);
    }
}

Notice that the implementation of PostMapper follows a fairly logical path. Simply put, not only does it extend its abstract parent, but it injects in the constructor a comment mapper (still undefined), in order to handle in sync both posts and comments without revealing to the outside world the complexities of creating the whole object graph. Of course, we shouldn’t deny ourselves the joy of seeing how the still veiled comment mapper looks, hence here’s its source code, coupled to the corresponding interface:

<?php
namespace ModelMapper;
use ModelCommentInterface;

interface CommentMapperInterface
{
    public function findById($id);
    public function findAll(array $conditions = array());

    public function insert(CommentInterface $comment, $postId,
        $userId);
    public function delete($id);
}
<?php
namespace ModelMapper;
use LibraryDatabaseDatabaseAdapterInterface,
    ModelCommentInterface,
    ModelComment;

class CommentMapper extends AbstractDataMapper implements CommentMapperInterface
{
    protected $userMapper;
    protected $entityTable = "comments";

    public function __construct(DatabaseAdapterInterface $adapter,
        UserMapperInterface $userMapper) {
        $this->userMapper = $userMapper;
        parent::__construct($adapter);
    }

    public function insert(CommentInterface $comment, $postId, 
        $userId) {
        $comment->id = $this->adapter->insert($this->entityTable, 
            array("content" => $comment->content,
                  "post_id" => $postId,
                  "user_id" => $userId));
        return $comment->id;
    }

    public function delete($id) {
        if ($id instanceof CommentInterface) {
            $id = $id->id;
        }

        return $this->adapter->delete($this->entityTable,
            "id = $id");
    }

    protected function createEntity(array $row) {
        $user = $this->userMapper->findById($row["user_id"]);
        return new Comment($row["content"], $user);
    }
}

The CommentMapper class behaves quite similar to its sibling PostMapper. In short, it asks for a user mapper in the constructor, so that a specific comment can be tied up to the corresponding commenter. Considering the easy-going nature of CommentMapper, let’s make a final effort and define another which will handle users:

<?php
namespace ModelMapper;
use ModelUserInterface;

interface UserMapperInterface
{
    public function findById($id);    
    public function findAll(array $conditions = array());
    
    public function insert(UserInterface $user);
    public function delete($id);
}
<?php
namespace ModelMapper;
use ModelUserInterface,
    ModelUser;

class UserMapper extends AbstractDataMapper implements UserMapperInterface
{    
    protected $entityTable = "users";

    public function insert(UserInterface $user) {
        $user->id = $this->adapter->insert($this->entityTable,
            array("name"  => $user->name,
                  "email" => $user->email));
        return $user->id;
    }

    public function delete($id) {
        if ($id instanceof UserInterface) {
            $id = $id->id;
        }
 
        return $this->adapter->delete($this->entityTable,
            array("id = $id"));
    }

    protected function createEntity(array $row) {
        return new User($row["name"], $row["email"]);
    }
}

Now that the UserMapper class is set, we’ve finally reached the goal we were committed to from the very start: build up from scratch an easy-to-massage mapping layer, capable of moving data back and forward between a simplistic blog domain model and MySQL. But let’s not pat ourselves in the back yet, as the best way to see if the mappers are as functional as they look at first blush is by example.

Mapping the Blog’s Domain Objects to and from the DAL

As you might expect, consuming the blog domain model in an efficient manner is pretty straightforward, as the mappers’ APIs do the actual hard work and hide the underlying database from the model itself. This ability, though, is best appreciated from the application layer’s perspective. Let’s wire up all the mapper graphs together:

<?php
use LibraryLoaderAutoloader;
require_once __DIR__ . "/Autoloader.php";
$autoloader = new Autoloader();
$autoloader->register();

// create a PDO adapter
$adapter = new PdoAdapter("mysql:dbname=blog", "myfancyusername",
    "myhardtoguesspassword");
 
// create the mappers
$userMapper = new UserMapper($adapter);
$commentMapper = new CommentMapper($adapter, $userMapper);
$postMapper = new PostMapper($adapter, $commentMapper);

So far, so good. At this point, the mappers have been initialized by dropping their collaborators into the corresponding constructors. Considering that they’re ready to get some real action, now let’s use the post mapper and insert a few trivial posts into the database:

<?php
$postMapper->insert(
    new Post(
        "Welcome to SitePoint",
        "To become yourself a true PHP master, you must first master PHP."));

$postMapper->insert(
    new Post(
        "Welcome to SitePoint (Reprise)",
        "To become yourself a PHP Master, you must first master... Wait! Did I post that already?"));

If all works as expected, the posts table should be nicely populated with the previous entries. But, is it just me or do they look a little lonely? Let’s fix that add a few comments:

<?php
$user = new User("Everchanging Joe", "joe@example.com");
$userMapper->insert($user);

// Joe's comments for the first post (post ID = 1, user ID = 1)
$commentMapper->insert(
    new Comment(
        "I just love this post! Looking forward to seeing more of this stuff.",
        $user),
    1, $user->id);

$commentMapper->insert(
    new Comment(
        "I just changed my mind and dislike this post! Hope not seeing more of this stuff.",
        $user),
    1, $user->id);

// Joe's comment for the second post (post ID = 2, user ID = 1)
$commentMapper->insert(
    new Comment(
        "Not quite sure if I like this post or not, so I cannot say anything for now.", 
        $user),
    2, $user->id);

Thanks to Joe’s remarkable eloquence, the first blog post should have now two comments and second should have one. Notice that the foreign keys used to sustain the bound between comments and users have been just picked up at runtime. In production, however, they most likely should be gathered inside the user interface.

Now that the blog’s database has been finally hydrated with a couple of posts, comments, and a chatty user’s info, the last thing we should do is pull in all the data and dump it on screen. Here we go:

<?php
$posts = $postMapper->findAll();

Even when this one-liner is… well just a one-liner, it’s actually the workhorse that creates blog domain object graphs on request from the database and put them in memory for further processing. On the other hand, the graphs in question can be easily decomposed back through a skeletal view, as follows:

<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <title>Building a Domain Model in PHP</title>
</head>
<body>
 <header>
  <h1>SitePoint.com</h1>
 </header>
 <section>
  <ul>
<?php
foreach ($posts as $post) {
?>
   <li>
    <h2><?php echo $post->title;?></h2>
    <p><?php echo $post->content;?></p>
<?php
	if ($post->comments) {
?>
    <ul>  
<?php
		foreach ($post->comments as $comment) {
?>
     <li>
      <h3><?php echo $comment->user->name;?> says:</h3>
      <p><?php echo $comment->content;?></p>
     </li>
<?php
		}
?>
    </ul>
<?php
	}
?>
    </li>
<?php
}
?>
   </ul>
  </section>
 </body>
</html>

Indeed, looping through a few posts, comments, and users is a boring task that doesn’t deserve any further explanation. Of course if you’re an insightful, hawk-eye observer, you might have noticed that this seemingly harmless view is in fact a hog eater which blatantly pulls in the entire database and throws it into the user interface’s heart. Let’s no rush to judgments since there are a few common tricks that can be used for tackling this issue, including caching (in any of its multiple forms), lazy-loading, and so forth.

Spicing up the data mappers with some of these goodies will be left as homework for you, something that surely will keep you entertained for quite a long time.

Closing Remarks

Very few will disagree that the implementation of a rich Domain Model is far away from being an overnight, high school-like task, even when using an easy-going language like PHP. While it’s safe to say that forwarding model data to and from the DAL can be delegated in many cases to a turnkey mapping library or framework (assuming there exists such a thing), defining the relationships between domain objects, as well as their own rules, data, and behavior is up to the developer.

Despite this, the extra effort in general causes a beneficial wave effect, as it helps out in pushing actively the use of a multi-tier design along with good OOP practices where the involved objects have just a few, well-defined responsibilities, and the model doesn’t get its pristine ecosystem polluted with database logic. Add to this that shifting the model from one infrastructure to another can be done in a fairly painless fashion, and you’ll get to see why this approach is very appealing when developing applications that must scale well.

Image via kentoh/ Shutterstock

Alejandro GervasioAlejandro Gervasio
View Author

Alejandro Gervasio is a senior System Analyst from Argentina who has been involved in software development since the mid-80's. He has more than 12 years of experience in PHP development, 10 years in Java Programming, Object-Oriented Design, and most of the client-side technologies available out there.

Expert
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week