Friends

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".

0 comments:

Twitter Delicious Facebook Digg Stumbleupon Favorites More