Home arrow PHP arrow Roll Your Own Repository in PHP: the Data Access Layer

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.

TABLE OF CONTENTS:
  1. Roll Your Own Repository in PHP: the Data Access Layer
  2. Building the data access layer
By: Alejandro Gervasio
Rating: starstarstarstarstar / 4
November 23, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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:

(Autoloader.php)

<?php

class Autoloader
{
    private static $_instance;
   
    /**
     * Get the Singleton instance of the autoloader
     */
    public static function getInstance()
    {
        if (self::$_instance === null) {
            self::$_instance = new self;
        }
        return self::$_instance;
    } 
   
    /**
     * Reset the instance of the autoloader
     */
    public static function resetInstance()
    {
        self::$_instance = null;
    }
   
    /**
     * Class constructor
     */
    private function __construct()
    {
        spl_autoload_register(array(__CLASS__, 'load'));
    }
   
    /**
     * Prevent cloning the instance of the autoloader
     */
    private function __clone(){}

    /**
     * Load a given class or interface
     */
    public static function load($class)
    {
        $file = $class . '.php';
        if (!file_exists($file)) {
            throw new ClassNotFoundException('The file containing the requested class ' . $class . 'or interface was not found.');
        }
        require $file;
        if (!class_exists($class, false) && !interface_exists($class, false)) {
            throw new ClassNotFoundException('The requested class or interface ' . $class . ' was not found.');
        }
    }  
}

 

(ClassNotFoundException.php)

<?php

class ClassNotFoundException extends Exception{}

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:

(EntityAbstract.php)

<?php

abstract class EntityAbstract
{
    protected $_values = array();
    protected $_allowedFields = array();
   
    /**
     * Class constructor
     */
    public function __construct(array $data)
    {
        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;   
        }
        if (array_key_exists($name, $this->_values)) {
            return $this->_values[$name];
        }
        throw new EntityException('The field ' . $name . ' has not been set for this entity yet.');
    }
       
    /**
     * Unset the specified property from the entity
     */  
    public function __unset($name)
    {
        if (array_key_exists($name, $this->_values)) {
            unset($this->_values[$name]);
        }
    }
      
    /**
     * 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:

(User.php)

<?php

class User extends EntityAbstract
{  
    protected $_allowedFields = array('id', 'fname', 'lname', 'email');
   
    /**
     * Set the user's ID
     */
    public function setId($id)
    {
        if(!filter_var($id, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 99999)))) {
            throw new EntityException('The specified ID ' . $id . ' is invalid.');
        }
        $this->_values['id'] = $id;
    }
   
    /**
     * Set the user's first name
     */ 
    public function setFname($fname)
    {
        if (strlen($fname) < 2 || strlen($fname) > 32) {
            throw new EntityException('The specified first name ' . $fname . ' is invalid.');
        }
        $this->_values['fname'] = $fname;
    }
       
    /**
     * Set the user's last name
     */
    public function setLname($lname)
    {
        if (strlen($lname) < 2 || strlen($lname) > 32) {
            throw new EntityException('The specified last name ' . $lname . ' is invalid.');
        }
        $this->_values['lname'] = $lname;
    }
   
    /**
     * Set the user's email address
     */
    public function setEmail($email)
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new EntityException('The specified email address ' . $email . ' is invalid.');
        }
        $this->_values['email'] = $email;
    }                   
}

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.      



 
 
>>> 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: