Friends

Quick Guide : Design Patterns for PHP


Design pattern provides useful ways for developing robust software faster along  with a way of encapsulating large ideas in friendly terms.  Most of the PHP programmer are not ware of the design patterns and how to implement those. So instead of going through the history and wasting more time in explanation, I will brief those patterns in short cut with examples.

The Factory pattern
The factory pattern is a class that has some methods that create objects for you. Instead of using new directly, you use the factory class to create objects. That way, if you want to change the types of objects created, you can change just the factory. All the code that uses the factory changes automatically.

What's the need to use Factory pattern?
Problem is tight coupling - Functions and classes in one part of the system rely too heavily on behaviors and structures in other functions and classes in other parts of the system. lots of code relies on a few key classes. Difficulties can arise when you need to change those classes. For example, suppose you have a User class that reads from a file. You want to change it to a different class that reads from the database, but all the code references the original class that reads from a file.

<?php
interface IUser
{
  function getName();
}

class User implements IUser
{
  public function __construct( $id ) { }

  public function getName()
  {
    return "Jack";
  }
}

class UserFactory
{
  public static function Create( $id )
  {
    return new User( $id );
  }
}

$uo = UserFactory::Create( 1 );
echo( $uo->getName()."\n" );
?>


Output
% php factory1.php 
Jack
%


Figure 1. The factory class and its related IUser interface and user class
The factory class and its related IUser interface and user class 

Advantage

suppose you need to first create the object and then set many attributes. This version of the factory pattern encapsulates that process in a single location so that the complex initialization code isn't copied and pasted all over the code base.

Listing 2. Factory2.php
<?php
interface IUser
{
  function getName();
}

class User implements IUser
{
  public static function Load( $id ) 
  {
        return new User( $id );
  }

  public static function Create( ) 
  {
        return new User( null );
  }

  public function __construct( $id ) { }

  public function getName()
  {
    return "Jack";
  }
}

$uo = User::Load( 1 );
echo( $uo->getName()."\n" );
?>


Output:

% php factory2.php 
Jack
%


Figure 2. The IUser interface and the user class with factory methods
The IUser interface and the user class with factory methods 









In my next part II will explain the Singleton pattern.


Part-II

0 comments:

Twitter Delicious Facebook Digg Stumbleupon Favorites More