Singleton Pattern in Zend Framework

The singleton provides a very good solution to the problem when you need an object to be handled as always single and global.

 

Singleton, which may usually merge up with other patterns (e.g. registry, factory), has been used in creating the independent objects for the application such as session and database connection etc..

 

Now let’s go and see how Zend_Controller_Front implements it in Zend Framework :

 

 

Code simplified :

 

class Zend_Controller_Front
{
    // Singleton instance
    protected static $_instance = null;

    // Constructor
    // Instantiate using {@link getInstance()}; front controller is a singleton object.
    protected function __construct()
    {
        ......
    }

    // Enforce singleton; disallow cloning
    private function __clone()
    {
    }

    // Singleton instance
    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    ......
}

 

We store the instance in a static variable that usually called $_instance and declared with protected or private. Then the getInstance() function is called to get the instance which will only be initialized once at the first time. This is so called "one and only one".

 

What we should notice is that the __clone() function is forbidden in the way declared with private which means we can’t clone the object and it’s instance anymore. And this is the "real" singleton.

 

We can now get the instance of Zend_Controller_Front only through Zend_Controller_Front::getInstance().

 

Posted in Design Patterns | Tagged , | Leave a comment