Tuesday, August 28, 2012

Singleton with PHP

        Singleton pattern is under creational design patterns which deals with mechanisms of creating objects according to the situation. I recently used this pattern with PHP. It's very important to get to know use of this pattern.

              Singleton pattern can be used for always keep one object of a specific class while an application is running. It save the memory which is going to allocate for new objects of the class in every where inside the application. Singleton practically used for logger classes which provide global logging access point whithout logging each and every application after the main loggin operation, configuration classes which consist configuration data of an application, access resources which are in shared mode like multi threading applications, Factory design pattern which dynamically create the objects etc.

         It's very easy to implement singleton with PHP (as well as other languages). What we need to do is make a private constructor and control the creating object of this class by a public method. Following code snippet shows how to do this.

class MySingleton {

    private static $instance = null;

    public static function getInstance() {
        if(is_null($this->instance)) {
            $this->instance = new MySingleton($params);
        }
        return $this->instance;
    }

    private function __construct($params) {
        // set parameters
    }

    public function doSomething() {
        // some code
    }

}

         Since the constructor is private only the class itself can be access the constructor. getInstance method is accessible for anywhere and since that is a static method it can be used anywhere without creating an object of this class. This function handles the situations of the need of a new instance of MySingleton class by calling the private constructor if needed. Static variable is used because of the restriction of using non-static fields inside static functions.

In the places where needs to call doSomething method in MySingleton class, we call as,
MySingleton::getInstance()->doSomething()
or, if the functions inside the class is frequently used,
$my_singleton = MySingleton::getInstance();
$my_singleton ->doSomething()

It's very simple. Hope this helpful. Have a fun with singleton. :)

4 comments:

  1. I think is good if you add a new method for cloning purpose:

    public function clone() {}

    ReplyDelete
    Replies
    1. Hi,
      In singleton pattern we create new object only if there is not already existing object. That is done by getInstance() method.
      In php the constructor is __construct() method which execute when creating new objects.
      Do you mean that put the code for creating new object to clone() method ? Not sure I get your point.

      Delete
  2. Wow amazing information about PHP development. PHP is best programming for custom website design in easy way so speedy also. PHP Application Development Company provide total solution for PHP.

    ReplyDelete
  3. Hi Chanaka,
    Great post!
    you have used `this` pointer inside a static function. Does php allow this?

    ReplyDelete