In Object Oriented Programming the Singleton design pattern answers to the problem of having a single or unique instance of a class in a program.
For example, as part of a dynamic web application, a database connection to the server is unique.
To preserve this uniqueness, it makes sense to use an object that takes the form of a singleton to create the sole representative object access to the database, and store the reference to it in a global variable of the program so that we can access it from anywhere in the script.
The Singleton design pattern implementation has three characteristics:
- A private static attribute that retain the unique instance of the class.
- A private constructor to prevent the creation of items from outside the class
- A static method to either instantiate the class is to return the unique instance created.
The code below shows a minimal class that incorporates the Singleton design pattern. We find the minimum, the three characteristics just presented above.
class Singleton
{
/**
* @var Singleton
* @access private
* @static
*/
private static $instance = null;
/**
* Private constructor: only to be created by myself
*
* @param void
* @return void
*/
private function __construct()
{
}
/**
* If it doesn't exits then creates one unique instance
* of this class, otherwise it returns the existant one.
*
* @param void
* @return Singleton
*/
public static function getInstance()
{
// If I am not created yet then I create myself
if(is_null(self::$instance)) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
// Try to get an instance of this class
Singleton::getInstance();
I've seen many uses of this design pattern, just a little word of warning: do not fall into "Singletonitis": willing to use this pattern for all your constants in your code. :)