IT Community - Software Programming, Web Development and Technical Support

What are the design patterns available in php?

This is a discussion on What are the design patterns available in php? within the PHP Programming forums, part of the Web Development category; There are 16 design patterns available. # The ValueObject Pattern # The Factory Pattern # The Singleton Pattern # The Registry Pattern # The MockObject ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > PHP Programming

Register FAQ Members List Calendar Mark Forums Read
  1 links from elsewhere to this Post. Click to view. #1 (permalink)  
Old 11-16-2007, 02:42 AM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Thumbs up What are the design patterns available in php?

There are 16 design patterns available.

# The ValueObject Pattern
# The Factory Pattern
# The Singleton Pattern
# The Registry Pattern
# The MockObject Pattern
# The Strategy Pattern
# The Iterator Pattern
# The Observer Pattern
# The Specification Pattern
# The Proxy Pattern
# The Decorator Pattern
# The Adapter Pattern
# The ActiveRecord Pattern
# The TableDataGateway Pattern
# The DataMapper Pattern
# The Model-View-Controller Pattern


Thanks,
Ramkumar.B

Last edited by ramkumaraol : 11-16-2007 at 02:45 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 11-16-2007, 10:38 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: What are the design patterns available in php?

The ValueObject pattern:

VOs are actually a J2EE pattern. It can easily be implemented in PHP. A value object corresponds directly to a C struct. It's a class that contains only member variables and no methods other than convenience methods (usually none). A VO corresponds to a business object. A VO typically corresponds directly to a database table. Naming the VO member variables equal to the database fields is a good idea. Do not forget the ID column.

PHP Code:
class Person {
  var 
$id$first_name$last_name$email;

Thanks,
Ramkumar.B

Last edited by ramkumaraol : 11-28-2007 at 06:10 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 11-16-2007, 10:58 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: What are the design patterns available in php?

Another example of Value Object pattern:
PHP Code:
<?php

/**
 *
 *
 * This object represents a company in the system.
 *
 *
 * Copyright (c) 2006 NeuralLimits
 *
 */
class Company {
    
/**
     * Persistent Instance variables. This data is directly
     * mapped to the columns of database table.
     */
    
var $companyid 00//
    
var $companyname ""//The Company Name
    /**
     * IsSet Instance variables. This data is directly
     * mapped to the columns of database table.
     */
    
var $companyidisSet false//
    
var $companynameisSet false//The Company Name
    /**
     * Constructor for Company
     */
    
function Company() {
    }
    
/**
     * Get- and Set-methods for persistent variables.
     */
    
function getCompanyID() {
        return 
$this->companyid;
    }
    function 
setCompanyID($companyidIn) {
        
$this->companyid $companyidIn;
        
$this->companyidisSet true;
    }
    function 
getCompanyName() {
        return 
$this->companyname;
    }
    function 
setCompanyName($companynameIn) {
        
$this->companyname $companynameIn;
        
$this->companynameisSet true;
    }
    
/**
     * isSet-methods for persistent variables.
     */
    
function getcompanyidisSet() {
        return 
$this->companyidisSet;
    }
    function 
getcompanynameisSet() {
        return 
$this->companynameisSet;
    }
    
/**
     * setAll allows to set all persistent variables in one method call.
     * This is useful, when all data is available and it is needed to
     * set the initial state of this object. Note that this method will
     * directly modify instance variales, without going trough the
     * individual set-methods.
     */
    
function setAll($companyidIn$companynameIn) {
        
$this->companyid companyidIn;
        
$this->companyidisSet true;
        
$this->companyname companynameIn;
        
$this->companynameisSet true;
    }
    
/**
    * hasEqualMapping-method will compare two Company instances
    * and return true if they contain same values in all persistent instance
    * variables. If hasEqualMapping returns true, it does not mean the objects
    * are the same instance. However it does mean that in that moment, they
    * are mapped to the same row in database.
    */
    
function hasEqualMapping($valueObject) {
        if (
$valueObject.getCompanyID() != $this->companyid) {
            return (
false);
        }
        if (
$valueObject.getCompanyName() != $this->companyname) {
            return (
false);
        }
        return 
true;
    }
    
/**
     * toString will return String object representing the state of this
     * valueObject. This is useful during application development, and
     * possibly when application is writing object states in textlog.
     */
    
function toString() {
        
$out "";
        
$out $out."class Company, representing table tcompany";
        
$out $out."Persistent attributes: ";
        
$out $out."companyid= ".$this->companyid."";
        
$out $out."companyname= ".$this->companyname."";
        return 
$out;
    }
    
/**
    * CloneCompany will return identical deep copy of this valueObject.
    */
    
function cloneCompany() {
        
$cloned = new Company();
        
$cloned->setCompanyID($this->companyid);
        
$cloned->setCompanyName($this->companyname);
        return 
$cloned;
    }
    
/**
     * toXML will return a String object as XML representing the state of this
     * valueObject.
     */
    
function toXML() {
        
$out "";
        
$out $out."<Company>\n";
        
$out $out." <CompanyID>".$this->companyid."</CompanyID>\n";
        
$out $out." <CompanyName>".$this->companyname."</CompanyName>\n";
        
$out $out."</Company>\n";
        return 
$out;
    }
    
/**
     * fromXML will accept a String of XML representing the state of this
     * valueObject and update the valueObject's values with the XML.
     */
    
function fromXML($valueObjectXML) {
        
$companyid_String substr($valueObjectXMLstrpos($valueObjectXML"<CompanyID>") + 10strpos($valueObjectXML"<CompanyID>") - 1);
        
$companyname_String substr($valueObjectXMLstrpos($valueObjectXML"<CompanyName>") + 12strpos($valueObjectXML"<CompanyName>") - 1);

        
$this->setCompanyID($companyid_String);
        
$this->setCompanyName($companyname_String);
    }
}
?>
Thanks,
Ramkumar.B

Last edited by ramkumaraol : 11-28-2007 at 06:11 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 11-18-2007, 10:24 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: What are the design patterns available in php?

The Factory pattern:

As you know, there are many approaches to building regular web forms. Commonly, we plan carefully what kind of data needs to be collected from users, then open our editor and write some (X)HTML code to display the proper form, including a few text boxes, radio buttons and so forth.

While this method may be quick and simple for implementing on small websites, when an application grows significantly in size, an object-based method is often much more efficient. If the program will use numerous forms for collecting user data, the form creation process might be reduced to something as simple as instantiating some form element objects and deciding the best layout for them.

The Factory pattern is very powerful and flexible, since it allows you to separate object instantiation from the rest of the client code. Generally speaking, this pattern is implemented through a class that accepts one or more parameters (inputs), and based on those parameters, determines what object to instantiate.

Due to the intrinsic power of the Factory pattern, I'm going to apply it in a concrete situation: the implementation of a "form element factory" that will take care of factoring each form component. Doing so, creation of forms can be noticeably simplified and translated into better code portability.

Thanks,
Ramkumar.B

Last edited by ramkumaraol : 11-28-2007 at 06:11 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 11-19-2007, 10:15 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: What are the design patterns available in php?

Factory pattern:

At some point in PHP development, programmers will discover a need to simplify the creation of some objects. Perhaps the object simply requires a number of detailed steps to create, all of which must be duplicated for every new object of that type. To remove such code duplication and simplify the task, the Factory Pattern offers a solution. In fact the Factory Pattern is something many programmers may discover by themselves since it is a logical step to take all the detailed creational steps of an object and try bundling into a new object to handle the task.

The Factory Pattern can be applied as an individual class with sole responsibility for creating objects or as a single method within the object to be created (a Factory Method). In both cases, its purpose remains similar - to make creating an object easier.
Definition

Definition: An object implementing the Factory Pattern is an object which creates other objects of a specific type.
Example

One family of objects whose creation may require numerous complex steps are from Database Abstraction libraries such as the ADOdb Lite or PEAR::MDB2. These libraries involve instantiating a connection object, allowing plugin use, and connecting to a database using configuration options. The steps involved can range from simple two liners to using complex logic depending on the scenario and plugins required.

Simplifying this process makes huge sense. One can write a dedicated Factory class to fetch configuration options and perform the instantiation and plugin tasks transparently (based on those options). A simple Factory interface and implementing class (with minimal tasks) for ADOdb Lite might look similar to:
PHP Code:
interface iFactory {
 
    public function 
createInstance();
 
}
 
class 
DatabaseAbstractionFactory implements iFactory {
 
    private 
$settings = array();
 
    public function 
__construct() {
        
// Settings class from our Singleton Pattern example
        
$this->settings Settings::getInstance();
    }
 
    public function 
createInstance() {
        require_once(
'/path/to/adodb_lite/adodb.inc.php');
        
$dsn $this->settings['db_dsnstring'];
        
// do lots of complicated stuff for adding plugins
        
$db ADONewConnection($dsn);
        return 
$db;
    }
 

Implementing the Factory Pattern

Of course, there are many other similar uses for a Factory. All that is required is that the Factory consolidate all the logic required to create an object. In the case above we have a single complex creation process for a Database Abstraction library's connection object. Another situation where a Factory is of use is where different objects of the same family must be created depending on some value.

For example, we may have a Logging utility which is capable of outputting a log message either to the browser or to the command line. Or perhaps we want it stored for later viewing to a file. The typical logic used within our calling class to determine which to use may be similar to:
PHP Code:
switch($outsetting)
{
    case 
'echo':
        
$out = new Output_Echo();
        break;
    case 
'cli':
        
$out = new Output_CLI();
        break;
    case 
'file':
        
$out = new Output_File();

This would work at first. But what happens if we decide we need to store the log message for later viewing in a database? Or maybe a client wants it output as formatted XML? As the options grow, this switch statement is growing ungainly. Worse, we may be replicating this piece of code across numerous classes which handle the initial generation or formatting of the log message. Any changes would need to be manually updated to all those classes.

The Factory Pattern suggests this creational logic should be isolated within its own class (the Factory) leaving the calling objects free to do their stuff and let the Factory worry about what Output object might be required.

The result may look similar to:
PHP Code:
interface iFactory {
 
    public function 
createInstance();
 
}
 
class 
Output_Factory implements iFactory {
 
    private 
$settings = array();
 
    public function 
__construct() {
        
$this->settings Settings::getInstance();
    }
 
    public function 
createInstance() {
        
$outsetting $this->settings->get('out.target');
        switch(
$outsetting)
        {
            case 
'echo':
                
$out = new Output_Echo();
                break;
            case 
'cli':
                
$out = new Output_CLI();
                break;
            case 
'file':
                
$out = new Output_File();
        }
        return 
$out;
    }
 

With all the troublesome logic hidden from the calling object and a standard interface implemented that is common to all Output classes, out calling classes (however many we have) are free to ignore everything except getting an Output class via the Factory and telling it to write something...
PHP Code:
class My_Log {
 
    private 
$output null;
 
    public function 
__construct() {
        
$factory = new Output_Factory();
        
$this->output $factory->createInstance();
    }
 
    public function 
log($message) {
        
$this->output->write($message);
    }
 

If creating the Factory manually turns annoying (being one extra line, and all programmers being exceptionally lazy), you could bundle the Settings class retrieval into the createInstance() method on the Factory class and make it a static method.

Thanks,
Ramkumar.B
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 11-19-2007, 10:20 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: What are the design patterns available in php?

Factory pattern:

Disadvantages

The Factory Pattern is a common pattern to see implemented. It is a logical method of isolating the logic for creating a class, or the logic for deciding which concrete subclass of a family to instantiate. In this capacity it has few disadvantages. Some problems may arise when complex creational logic of various types co-exist - i.e. where it becomes necessary to utilise two or more Factory classes.

One example might be our Database Abstraction Factory. It's sole purpose is to churn out ADOdb Lite connection objects applying configuration options, loading required plugins (if such added), etc. If someone were to decide that they needed access to PEAR::MDB2 or the traditional ADOdb library then the creational logic for instantiation and plugin loading would differ. Although this new piece of logic (deciding which library to use) could be integrated into the existing Factory class - it would simply turn into a very complex switch statement.

Thanks,
Ramkumar.B
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 11-23-2007, 01:07 AM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: What are the design patterns available in php?

Singleton Pattern:

The Singleton is one of the simplest Patterns to understand. It's common usage is to ensure that only one instance of a class is ever instantiated. The reason for wanting such behaviour varies but typically it is because only one object instantiated from the source class is required and you want the resulting object to be available throughout an application, i.e. globally available.

An example might be a class for storing Settings. A Settings class is a good candidate for a Singleton because its data is immutable (the only way to change settings data is to edit the settings file) and it is likely required in many areas of an application. Furthermore creating a new Settings object wherever it is needed is wasteful of resources - each is identical to all others.
Definition

Definition: The Singleton Pattern proposes a static method for creating an instance of a class in such a way that once instantiated further calls to the same static method return a reference to the original instantiated object.

Thanks,
Ramkumar.B

Last edited by ramkumaraol : 11-28-2007 at 06:12 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 11-26-2007, 10:06 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: What are the design patterns available in php?

Example for Singleton Pattern:
PHP Code:
class Settings (
 
    private 
$settings = array();
 
    private static 
$_instance null;
 
    private function 
__construct() {
        
// private constructor restricts instantiaton to getInstance()
    
}
 
    protected function 
__clone() {
        
// restricts cloning of the object
    
}
 
    static public function 
getInstance() {
        if(
is_null(self::$_instance))
        {
            
self::$_instance = new self();
        }
        return 
self::$_instance;
    }
 
    public function 
import() {
        
// ...
    
}
 
    public function 
get() {
        
// ...
    
}
 

Thanks,
Ramkumar.B
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 11-27-2007, 10:00 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: What are the design patterns available in php?

Implementing the Singleton Pattern
The key to implementing a Singleton is utilising a static variable; a variable whose value remains constant even when execution leaves its variable scope. This stores the object originally instantiated between calls to the static method Settings::getInstance(), and returns a reference to it on each subsequent call to the method.

Also note that the constructor is usually made private. To ensure only one Settings object is ever used, we should restrict access to the constructor to prevent a new object being created in error. This specific restriction is not possible in PHP 4 so bear this in mind.

The Singleton also requires careful consideration before use. It is by nature very similar to a global variable - the static method is available from anywhere in the application once the file containing the class is included. This can create problems similar to those experienced with global variables - and so should be used with some degree of care. The near global nature of the Singleton has led to it being referred to on occassion as an "Anti Pattern" since it is easily misused as an alternative to making data global.

Using a Singleton is as simple as calling its static getInstance() method.
PHP Code:
// fetch settings from INI file
$settings Settings::getInstance();
$settings->import('/app/settings.ini');
 
// we can now use the Settings object somewhere else, e.g. database class
class DB_Abstraction_MYSQLI {
 
    private 
$settings null;
 
    public function 
__construct() {
        
// Settings already exists with imported settings data
        // Fetch pre-existing object via Singleton method
        
$this->settings Settings::getInstance();
    }
 
    public function 
connect() {
        
$conn mysqli_connect(
            
$this->settings->get('db.host'),
            
$this->settings->get('db.username'),
            
$this->settings->get('db.password'),
            
$this->settings->get('db.database')
        );
        return 
$conn;
    }
 
    
// ...
 

The alternative to using the Singleton is of course to instantiate a Settings object, and import the settings INI file again. However doing so only wastes resources since the data is immutable and identical to that held in all such objects. Why have a dozen identical Settings objects when you only need one?

Thanks,
Ramkumar.B
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 11-28-2007, 10:08 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: What are the design patterns available in php?

Disadvantages of Singleton Pattern:
The Singleton is not without its disadvantages. We have already noted that its global nature can cause problems similar to using global variables and encourage misuse without care. It can also make the practice of Unit Testing more difficult. Unit Testing typically tests individual objects. In testing the DB_Abstraction class above, a programmer may wish to "mock" the Settings object (i.e. insert a fake object with known return values). This is useful in cases where the Settings class may not even yet exist, and we need to emulate it.

One solution, is to amend the class so that a developer may optionally pass a Settings object as a paramater into the constructor. The code for this may look similar to:
PHP Code:
class DB_Abstraction_MYSQLI {
 
    
// ...
 
    
public function __construct($settings=null) {
        
$this->settings is_null($settings) ? Settings::getInstance() : $settings;
    }
 
    
// ...
 

This allows more flexible testing since a developer can optionally override the default behaviour of using the Settings class Singleton method, and replace it with any arbitrary Settings object they choose to facilitate testing.
Thanks,
Ramkumar.B
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #11 (permalink)  
Old 11-29-2007, 09:36 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: What are the design patterns available in php?

Registry Pattern:
The Registry is one of those Patterns where once you understand it, it seems so incredibly useful. Think of it as a basket; using a Registry you can add data (both values and objects) to the basket, and retrieve them as required from other parts of an application. Since all such data is handled by a single Registry object, it makes passing data and objects around an application far more simple than passing all such values as individual parameters to a constructor or setup method. In a similar fashion, a Registry can replace the need to have every object you need global access to acting as a Singleton.

The Registry itself can either be passed around as a parameter or it can be turned into a Singleton to enable global access to it from anywhere in an application. Where it is used to replace numerous Singletons, it can replace the need to know each individual class name which often makes it easier to reuse classes in other applications.
Definition

Definition
: The Registry Pattern allows the storing and retrieval of data and objects which need to be accessed globally in a single centralised object.
Thanks,
Ramkumar.B
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 12-02-2007, 10:24 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: What are the design patterns available in php?

Example of Registry Pattern:
At a minimum a Registry allows data to be registered and retrieved, often allowing the setting of a label for the value being registered. One of the most common types of data to use a Registry for are objects for which global access from other objects is required.

This simple PHP 5 example implements a private array to store objects and four methods for registering, unregistering, retrieving and checking the existence of objects.
PHP Code:
class My_Registry {
 
    private 
$store = array();
 
    public function 
__construct() {
 
    }
 
    public function 
register($label$object) {
        if(!isset(
$this->store[$label]))
        {
            
$this->store[$label] = $object;
        }
    }
 
    public function 
unregister($label) {
        if(isset(
$this->store[$label]))
        {
            unset(
$this->store[$label]);
        }
    }
 
    public function 
get($label) {
        if(isset(
$this->store[$label]))