Friday, 2 March 2012

Database connection using the Singleton pattern

The Singleton is, probably, the simplest design pattern. Its goal is to provide access to a single resource that is never duplicated, but that is made available to any portion of an application that requests it without the need to keep track of its existence. The most typical example of this pattern is a database connection, which normally only needs to be created once at the beginning of a script and then used throughout its code. With the singleton pattern, an object is instantiated when you first call for it (known as lazy loading); from that point on, each call will return the same object.

Here’s an example how to use this pattern in PHP in a database connection:

<?php

class DB
{
       private static $_instance=NULL;
       private function __construct()
       {
          self::$_instance=new mysqli('localhost', 'root', '', 'test');       
       }
      
       public static function getInstance()
       {
              if(self::$_instance == NULL)
              {
                     new DB();
              }
              return self::$_instance;
       }
}

?>

To use the singleton, because static methods are accessible within the global scope, wherever we want a database connection, we can simply call DB::getInstance().

$connection=DB::getInstance();

No comments:

Post a Comment

document.write() overwrites the entire page

document.write is a function which basically outputs whatever is given to it. But sometimes, improper usage may overwrite the entire page d...