Friends

Quick Guide : Design Patterns for PHP - part III

The observer pattern
why?
To define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
One object makes itself observable by adding a method that allows another object, the observer, to register itself. When the observable object changes, it sends a message to the registered observers.

The participants classes in this pattern are:
Observable - interface or abstract class defining the operations for attaching and de-attaching observers to the client. 
ConcreteObservable - concrete Observable class. It maintain the state of the object and when a change in the state occurs it notifies the attached Observers.
Observer - interface or abstract class defining the operations to be used to notify this object.

A simple example is a list of users in a system. The code in Listing 4 shows a user list that sends out a message when users are added. This list is watched by a logging observer that puts out a message when a user is added.
Listing 4. Observer.php

<?php
interface IObserver
{
  function onChanged( $sender, $args );
}

interface IObservable
{
  function addObserver( $observer );
}

class UserList implements IObservable
{
  private $_observers = array();

  public function addCustomer( $name )
  {
    foreach( $this->_observers as $obs )
      $obs->onChanged( $this, $name );
  }

  public function addObserver( $observer )
  {
    $this->_observers []= $observer;
  }
}

class UserListLogger implements IObserver
{
  public function onChanged( $sender, $args )
  {
    echo( "'$args' added to user list\n" );
  }
}

$ul = new UserList();
$ul->addObserver( new UserListLogger() );
$ul->addCustomer( "Jack" );
?>


Output:

% php observer.php 
'Jack' added to user list
%

This code defines four elements: two interfaces and two classes. The IObservable interface defines an object that can be observed, and the UserList implements that interface to register itself as observable. The IObserver list defines what it takes to be an observer, and the UserListLogger implements that IObserver interface. This is shown in the UML in Figure 4.

Figure 4. The observable user list and the user list event logger
The observable user list and the user list event logger


The test code creates a UserList and adds the UserListLogger observer to it. Then the code adds a customer, and the UserListLogger is notified of that change.
It's critical to realize that the UserList doesn't know what the logger is going to do. There could be one or more listeners that do other things



In next post I will explain the forth design pattern "The chain-of-command pattern".



Quick Guide : Design Patterns for PHP - part II

The Singleton Pattern

Why?
1. If are using a reference to an object in mulitple location and you don't want the overhead of creating a new instance of that object for each refrence
e.g. Database connection object
2. To pass the objects state from one reference to another instead of starting from an initial state.

The singleton pattern covers this need. An object is a singleton if the application can include one and only one of that object at a time.

<?php
require_once("DB.php");

class DatabaseConnection
{
  public static function get()
  {
    static $db = null;
    if ( $db == null )
      $db = new DatabaseConnection();
    return $db;
  }

  private $_handle = null;

  private function __construct()
  {
    $dsn = 'mysql://root:password@localhost/photos';
    $this->_handle =& DB::Connect( $dsn, array() );
  }
  
  public function handle()
  {
    return $this->_handle;
  }
}

print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
?>


Output
% php singleton.php 
Handle = Object id #3
Handle = Object id #3
%
This code shows a single class called DatabaseConnection. You can't create your own DatabaseConnection because the constructor is private. But you can get the one and only one DatabaseConnection object using the static get method.

The database connection singleton
The two handles returned are the same object. If you use the database connection singleton across the application, you reuse the same handle everywhere.
You could use a global variable to store the database handle, but that approach only works for small applications. In larger applications, avoid globals, and go with objects and methods to get access to resources.

In next post I will explain the third design pattern "The observer pattern".

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

Twitter Delicious Facebook Digg Stumbleupon Favorites More