Home arrow PHP arrow Creating a Basic Data Access Layer in PHP and MySQL

Creating a Basic Data Access Layer in PHP and MySQL

In this third installment of the series, I develop a basic data access layer using PHP and MySQL. It is made up of a single interface and an implementer of it, which in this case is a simple MySQL abstraction class. The construction of this additional layer takes us one step closer to developing a UoW that can be used in a truly helpful fashion.

TABLE OF CONTENTS:
  1. Creating a Basic Data Access Layer in PHP and MySQL
  2. Talking to the persistence layer: defining a basic database interface
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
December 29, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

If you frequently build large PHP applications whose domain layers are composed of a huge variety of domain objects, it's probable that you're desperately in search of an approach that helps you to optimize the interactions that those objects have with the underlying persistence mechanism.

Leave your pain behind and enter the world of a Unit of Work (UoW). This enterprise-level design pattern will let you easily create an in-memory map of domain objects that must be inserted, updated and deleted from the data access layer. The beauty of this schema is that all of these operations will be performed through a single method call, thus reducing the overhead caused by expensive (and sometimes unnecessary) database trips.

Despite the apparent complexity involved in the construction of a UoW, most of its logic can be implemented via some straightforward methods that are only responsible for manipulating plain array elements. Since the best way to prove my statement is by showing some functional code snippets, in earlier chapters of this series I went through the development of an abstract UoW class, capable of queuing objects for further insertion, updating and removal.

With this base structure existing in the form of a generic service, it was fairly easy to complement its functionality by adding to it the collaborators that it required to function properly. The first of these dependencies was a simple data mapper, tasked with interacting  with the persistence layer. The second one was an abstract class whose main responsibility was to model generic entities.

Of course, there's still a lot more work that needs to be done before you see the actual benefits of using a UoW. This includes the creation of a basic -- yet functional -- database adapter. Since I want to keep things simple and easy to follow, the adapter that I plan to construct in the lines to come will be comprised of only a MySQL abstraction class, which you'll be able to tweak and enhance at will afterwards.

It's time to continue this educational journey that shows you how to build a UoW in PHP. Let's go!

Review: adding a couple of collaborators to the previous Unit of Work

In the introduction, I mentioned that the sample UoW previously developed injects two additional dependencies through its constructor, which make it work properly. The first of these collaborators is an abstract data mapper. Its definition has been included below, in case you don't recall how it looks. Here it is: 

(DataMapperAbstract.php)

<?php

abstract class DataMapperAbstract
{
    protected $_adapter;
    protected $_collection;
        
    /**
     * Class constructor
     */
    public function __construct(DatabaseAdapterInterface $adapter, CollectionAbstract $collection)
    {
        $this->_adapter = $adapter;
        $this->_collection = $collection;
        $this->init();
    }
   
    /**
     * Initialize the data mapper here
     */
    public function init(){}
   
    /**
     * Get the instance of the database adapter
     */ 
    public function getAdapter()
    {
        return $this->_adapter;
    }
   
    /**
     * Get the collection
     */
    public function getCollection()
    {
        return $this->_collection;
    } 
}

Definitely, understanding how the above abstract mapper works is a very simple process.It acts like a mediator between the UoW and the persistence layer, which is also capable of dealing with collections of entities. Considering that the UoW performs CRUD operations on the entities in question, there must exist a class that allows you to create them and assign values to their fields, right? Well, the one shown below does exactly that: 

(EntityAbstract.php)

<?php

abstract class EntityAbstract
{
    protected $_values = array();
    protected $_allowedFields = array();
   
    /**
     * Class constructor
     */
    public function __construct(array $data = array())
    {
        foreach ($data as $name => $value) {
            $this->$name = $value;
        }
    }
   
    /**
     * Assign a value to the specified field via the corresponding mutator (if it exists);
     * otherwise, assign the value directly to the '$_values' protected array
     */
    public function __set($name, $value)
    {  
        if (!in_array($name, $this->_allowedFields)) {
            throw new EntityException('The field ' . $name . ' is not allowed for this entity.'); 
        }
        $mutator = 'set' . ucfirst($name);
        if (method_exists($this, $mutator) && is_callable(array($this, $mutator))) {
            $this->$mutator($value);          
        }
        else {
            $this->_values[$name] = $value;
        }   
    }
   
    /**
     * Get the value assigned to the specified field via the corresponding getter (if it exists);
    otherwise, get the value directly from the '$_values' protected array
     */
    public function __get($name)
    {
        if (!in_array($name, $this->_allowedFields)) {
            throw new EntityException('The field ' . $name . ' is not allowed for this entity.');   
        }
        $accessor = 'get' . ucfirst($name);
        if (method_exists($this, $accessor) && is_callable(array($this, $accessor))) {
            return $this->$accessor;   
        }
        return array_key_exists($name, $this->_values) ?
               $this->_values[$name] :
               null;
    }
   
    /**
     * Get an associative array with the values assigned to the fields of the entity
     */
    public function toArray()
    {
        return $this->_values;
    }             
}

 

(EntityException.php)

<?php

class EntityException extends Exception {}

Mission accomplished, at least for the moment. With the inclusion of the above "EntityAbstract" class, I finished this quick review of the dependencies that the sample UoW requires to correctly do its business. So, what's next? Well, as you may have noticed, the earlier data mapper also injects a collaborator into its internals, which happens to be an instance of a database interface.

Since this interface and its eventual implementer(s) are tasked with talking directly to the persistence mechanism, it's necessary to show their respective definitions, so you can see how they sit down below the mapping layer. Don't be worried, though, as this will be done in the following section.

Now, go ahead and read the next few lines.  



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: