Showing posts with label php design patterns. Show all posts
Showing posts with label php design patterns. Show all posts

Wednesday, August 1, 2012

Database Access Object Pattern using PHP


The simplest web widget to the most complex online e-commerce website have one thing in
common: they deal with data. So much of programming revolves around data access and
manipulation. With the massive proliferation of the Internet, cheaper storage devices, improved understanding of analytics, and greater expectations for information access, data is being leveraged in more interesting and unique ways. The Data Access Object Design Pattern aims to help construct objects that can work easily (transparently) with all of this data.

Programming typically can be a lot of repetition. This was especially true before more popular frameworks started being released. Most PHP programmers can count into the double digits the number of CRUD (create, read, update, delete) applications they’ve had to make. One of the major portions of repetition in the standard create/update application is the data source manipulation. For the rest of the discussion, I’m going to stop generalizing the data source and refer to it as SQL.

In the application, a SQL statement has to be written to create the entity in the database. Next, an additional SQL statement must be written in order to provide updates to any of the individual features of that entity. The repetition involved in creating these SQL statements is not only boring but also not best practice.

Code example

First create your own database and create following table

 CREATE TABLE task (  
      id INT PRIMARY KEY AUTO_INCREMENT,  
      subject VARCHAR(255),  
      description text  
 );  

Create php file called "baseDao" and put following code

 <?php  
 class baseDao  
 {  
   private $connection;  
   public function __construct() {  
     $this->connectToDb(DB_USER, DB_PASS, DB_HOST, DB_NAME);  
   }  
   public function connectToDb($user, $pass, $host, $database) {  
     $this->connection = mysql_connect($host, $user, $pass);  
     mysql_select_db($database, $this->connection);  
   }  
   public function fetch($value, $key = NULL)  
   {  
     if (is_null($key)) {  
       $key = $this->_primaryKey;  
     }  
     $sql = "SELECT * FROM {$this->_tableName} WHERE {$key} = '" . $value . "';";  
     $results = mysql_query($sql, $this->connection);  
     $rows = array();  
     while ($result = mysql_fetch_array($results)) {  
       $rows[] = $result;  
     }  
     return $rows;  
   }  
   public function update($keyedArray)  
   {  
     $sql = "UPDATE {$this->_tableName} SET ";  
     $updates = array();  
     foreach ($keyedArray as $column=>$value) {  
       $updates[] = "{$column}='" . $value . "'" ;  
     }  
     $sql .= implode(",", $updates);  
     $sql .= " where {$this->_primaryKey}='". $keyedArray[$this->_primaryKey] . "';";  
     mysql_query($sql, $this->connection);  
   }  
      public function save($keyedArray)  
   {  
     $sql = "INSERT INTO {$this->_tableName} ";  
     $updates = array();  
     foreach ($keyedArray as $column=>$value) {  
       $updates_columns[] = "{$column}";  
       $updates_values[] = "'" . $value . "'" ;  
     }  
           $sql .= "(";  
     $sql .= implode(",", $updates_columns);  
           $sql .= ")";  
           $sql .= " VALUES (";  
     $sql .= implode(",", $updates_values);  
     $sql .= ");";  
     if (!mysql_query($sql, $this->connection))  
                echo mysql_error();  
   }  
 }  

Finally you can use the dao class as follows:


 <?php  
 //DB_USER, DB_PASS, DB_HOST, DB_NAME  
 define('DB_USER', 'root');  
 define('DB_PASS', '');  
 define('DB_HOST', 'localhost');  
 define('DB_NAME', 'blog_samples');  
 //include "baseDao.php";  
 include "taskDao.php";  
 $taskDao = new taskDao();  
 $updates=array('subject' => 'testSubjectValue', 'description' => 'testDescriptionValue');  
 $taskDao->save($updates);  
 echo "<br/>Dao pattern !<br/>";  
Good luck !

Friday, July 27, 2012

Builder design pattern using php

Software complexity is an interesting thing. The requirements for software are complex as are the functionality of a software package or product. Even the code that makes up the software is complex. The focus of the Design Pattern approach is to provide maintainability, architectural 
strength and reduced complexity. With the host of complex objects making up most software repositories, solutions involving the Builder Design Pattern have their work cut out for them.

Code example

The project contains a class that creates the complex product object. This class contains three methods to completely form it. If each of these methods is not called when creating a new product object, attributes of the class will be missing and the program will halt. These methods are setType(), setColor(), and setSize(). The initial version of this code was designed to create the object followed by the execution of each of these methods.

class Product
{
    protected $type = '';
    protected $size = '';
    protected $color = '';
    protected $price = '';

    public function setColor($color)
    {
        $this->color = $color;
    }

    public function setSize($size)
    {
        $this->size = $size;
    }

    public function setType($type)
    {
        $this->type = $type;
    }


    public function setPrice($price)
    {
        $this->price = $price;
    }

    function __toString()
    {
        $text = 'Product { ';
        $text .= ":type => " . $this->type;
        $text .= ", :size => " . $this->size;
        $text .= ", :color => " . $this->color;
        $text .= ", :price => " . $this->price;
        $text .= " }";
        return $text;
    }

}


To create a complete product object, the product configurations need to be passed individually to each of
the methods of the product class:


// our product configuration received from other functionality
$productConfigs = array(‘type’=>’shirt’, ‘size’=>’XL’, ‘color’=>’red’);
$product = new product();
$product->setType($productConfigs[‘type’]);
$product->setSize($productConfigs[‘size’]);
$product->setColor($productConfigs[‘color’]);


Having to call each one of these methods when an object is created is not best practice. Instead, an object based on the Builder Design Pattern should be used to create this product instance.


The productBuilder class is designed to accept those configuration options that are required to build
the product object. It stores both the configuration parameter and a new product instance on
instantiation. The build() method is responsible for calling each of the methods in the product class to
fully complete the product object. Finally, the getProduct() method returns the completely built
product object.




class ProductBuilder
{

    protected $product = NULL;
    protected $config = array();

    public function __construct($config){
        $this->product = new Product();
        $this->config = $config;
    }

    public function build() {
        $this->product->setType($this->config['type']);
        $this->product->setColor($this->config['color']);
        $this->product->setSize($this->config['size']);
        $this->product->setPrice($this->config['price']);
    }

    public function getProduct() {
        return $this->product;
    }
}

Note that this build() method hides the actual method calls from the code requesting the new product. If the product class changes in the future, only the build() method of the productBuilder class needs to change. This code demonstrates the creation of the product object, using the productBuilder class:


$builder = new productBuilder($productConfigs);
$builder->build();
$product = $builder->getProduct();

The Builder Design Pattern is meant to eliminate the complex creation of other objects. Using the Builder Design Pattern is not only best practice but it also reduces the chances of having to repeatedly alter pieces of code if an object’s construction and configuration methods change.

Friday, May 11, 2012

Adapter pattern using php

Programming would be simple, but boring. Programmers would continue to build applications on top of the same technologies that they did years ago. They would never need to introduce different databases, implement new best practices, or consume different APIs. But these things do change. Luckily, programmers have the Adapter Design Pattern to help update legacy systems with new code and functionality.

The solution is to build another object, using the Adapter Design Pattern. This Adapter object works as an intermediary between the original application and the new functionality. The Adapter Design Pattern defines a new interface for an existing object to match what the new object requires.

Code Example

In the original code base of the project, an object exists that handles all of the error messages and codes called errorObject. The original programmers didn’t think their code would ever generate any errors, so they designed the system to output the errorObject’s error information directly to the console.

In this example, a 404:Not Found error is being generated. You are going to assume that the error message content and code may change, but the text will always stay in the same format.

 class ErrorObject  
 {  
   private $error;  
   public function __construct($error){  
     $this->error = $error;  
   }  
   public function getError(){  
     return $this->error;  
   }  
 }  


 class LogToConsole  
 {  
   private $errorObject;  
   public function __construct($errorObject){  
     $this->errorObject = $errorObject;  
   }  
   public function write() {  
     fwrite(STDERR, $this->errorObject->getError() . "\n");  
   }  
 }  

Here is the testing...

 include "ErrorObject.php";  
 include "LogToConsole.php";  
 /** create the new 404 error object **/  
 $error = new ErrorObject("404:Not Found");  
 /** write the error to the console **/  
 $log = new LogToConsole($error);  
 $log->write();  
How about new requirement comes that error need to output to csv format, with the code and description.
Lets look at how we going to do that with Adapter pattern.
 class LogToCsvAdapter extends ErrorObject  
 {  
   private $errorNumber, $errorText;  
   public function __construct($error)  
   {  
     parent::__construct($error);  
     $parts = explode(':', $this->getError());  
     $this->errorNumber = $parts[0];  
     $this->errorText = $parts[1];  
   }  
   public function getErrorNumber()  
   {  
     return $this->errorNumber;  
   }  
   public function getErrorText()  
   {  
     return $this->errorText;  
   }  
 }  






Here is the testing...
 include "ErrorObject.php";  
 include "LogToCsv.php";  
 include "LogToCsvAdapter.php";  
 /** create the new 404 error object adapted for csv **/  
 $error = new LogToCsvAdapter("404:Not Found");  
 /** write the error to the csv file **/  
 $log = new logToCSV($error);  
 $log-&gt;write();  




Good luck...