Login

Roll Your Own Repository in PHP: the Data Access Layer

In this second installment of the series, I create a simple data access layer. It will be comprised of a single interface, and a basic MySQL abstraction class.

A repository is an abstraction layer that usually sits between the domain and the mapping layers of a given application. It provides client code with a set of methods that can be used to manipulate collections of domain objects that match a specific criteria. Superbly described by Martin Fowler in his already classic book Patterns of Enterprise Application Architecture, a repository can be really helpful for encapsulating queries on related domain objects behind an intuitive API. Doing this produces an illusion of having all of those object collections residing in memory at the same time.

As with other software design patterns, a repository can be implemented in multiple programming languages. This includes PHP — though PHP-based repositories aren’t very popular right now, except in cases where this level of abstraction is indispensable. Regardless, building a repository from scratch in PHP is an extremely productive process. It permits you to put other principles and patterns of modern application development to work together, such as data mappers, factories and entities, beyond the typical implementation of Active Record. Note that a typical implementation of Active Record couples domain objects “too dangerously” with the underlying persistence mechanism (usually a relational database).

With that premise in mind, in the first part of this series I took the first step toward the construction of a simple user repository, namely the development of the domain layer. To keep the process easy to follow, the layer was comprised of two sample classes. The first one was an abstract parent, tasked with defining the structure and behavior of generic entities, while the second class was a refined implementation of the parent, responsible for modeling basic user objects.

Needless to say, before I manage to create a functional user repository, there are some additional steps that must be taken. These include (among others) building the data access and mapping layers. Therefore, in this second tutorial of the series, I’m going to create the former; for the sake of simplicity, it will be made up of a simple MySQL abstraction class.

Ready to see how this sample data access layer will be built in a few easy steps? Then jump in and begin reading!

Reviewing the sample classes defined so far

Before I start defining the data access layer mentioned in the introduction, let’s quickly review the classes created in the preceding part of the series. As you’ll recall, these classes comprise the domain layer of this example. Their responsibility is to create simple entities, like the user objects that will be handled later on by the repository.

With that said, first, here’s a basic autoloader. It lazy-loads source classes via the SPL stack. Check it out:

As you’ll surely agree with me, the logic implemented by the above “Autoloader” class is very easy to grasp, so I’m not going to waste your valuable time explaining how it works again. Instead, look at the following two classes. The abstract one, “EntityAbstract,” is tasked with defining the structure and behavior of generic entities, while the concrete “User” class is charged with modeling user objects. Here’s the former:

/**
* Get the values assigned to the fields of the entity
*/
public function toArray()
{
return $this->_values;
}
}

(EntityException.php)

<?php

class EntityException extends Exception {}

Done. With the above abstract parent encapsulating most of the functionality required to create generic entities, deriving a subclass that models user objects according to a number of predefined constraints is this easy:

Mission accomplished, at least for now. Having shown the pair of classes that make up the domain layer of this example (plus the autoloader, which normally should reside in some kind of bootstrap module or class), the next step is to define the corresponding data access layer. As mentioned before, this layer will be integrated by a basic MySQL abstraction class.

Don’t be concerned for the moment if these layers seem to be disconnected from each other. When I put them to work side by side, you’ll see how nicely they’ll fit in the whole schema imposed by a repository.

So, if you want to see the definition of the aforementioned data access layer, read the following segment. It’s only one click away.

{mospagebreak title=Building the data access layer}

In reality, before creating a concrete class tasked with talking directly to MySQL, we need to define a simple contract. This contract must be implemented by this class, and by other classes responsible for interacting with different RDBMS. In doing so, it’ll be possible to create easily “pluggable” database adapters that aren’t tied to a specific implementation.

For obvious reasons, the contract is nothing but an interface, whose definition looks like this:

As you can see above, the “DatabaseAdapterInterface” interface defines a set of methods which must be implemented later by any adapter class that works with a specific database server. In many popular frameworks, such as the Zend Framework and Symfony, common functionality shared by different database adapters is usually encapsulated within an abstract class. Since in this case I plan to use only a single MySQL adapter, I decided to define a single interface, which is open to further implementations.

So far, so good. Now that you understand the purpose of coding the previous interface, it’s time to create the MySQL abstraction class mentioned before.

The source code of this class will be shown in the next section. Thus, to get there, just keep reading.

Creating an implementer of the previous interface: building a basic MySQL abstraction class

For demonstration purposes, the underlying persistence mechanism that will be used for storing and retrieving all of the user objects spawned from the “User” class will be a MySQL database. Therefore, it’s mandatory to build a class capable of interacting with that database server through a simple API.

This class is naturally an implementer of the previous “DatabaseAdapterInterface” interface. Its source code is shown below:

/**
* Close automatically the database connection when the instance of the class is destroyed
*/
public function __destruct()
{
$this->disconnect();
}
}

(MySQLAdapterException.php)

<?php

class MySQLAdapterException extends Exception{}

Don’t feel overwhelmed by the rather lengthy definition of the above “MySQLAdapter” class. The logic that drives it is fairly easy to follow, trust me. Basically, the class is a simple wrapper for the “mysqli” PHP extension, which exposes a set of discrete methods that perform some common operations on the database server. These operations include fetching table rows, executing selects, insertions/updates and deletions. Naturally, it’s possible to swap this database class with the one included with the framework of your choice (if you use one), so feel free to skip over this explanation.

Anyway, with the inclusion of the “MySQLAdapter” class, the data access layer of this example is now complete. Even though it’s valid to note that the pair of sample layers defined so far can’t work together yet, their respective implementations have brought us closer to the construction of a user repository. At the risk of being repetitive, bear in mind that this is a step-by-step development process, so be patient for now. In the end, the wait will be really worthwhile.

Final thoughts

In this second installment of the series, I created a simple data access layer. It was comprised of a single interface and a basic MySQL abstraction class whose underlying logic was hopefully easy to catch.

Having already created two independent sample layers, the next logical step is to define one more, responsible for talking to both while keeping them isolated from each other. As you may have guessed, this extra layer will be composed of the data mappers, and in the course of the coming tutorial I’ll show you how to implement them in a pretty straightforward fashion.