The Singleton Pattern: OOP Techniques in PHP


The singleton pattern is a common pattern used to make resources exclusive in that there is one of a particular type of resource. The most common usage of this is database connectivity. Typically, an application only wants a single connection to a single database server at any given time. Another use could be restricting the instance to a specific number of objects. This is where the singleton pattern comes in.
The singleton pattern is defined as a design pattern that is used to restrict instantiation of a class to one object (or limit number of instances). This is a pretty straight forward concept and works well with many other OOP techniques including the factory pattern. The easiest implementation is to create a public static method within that class that instantiates a new instance.
Example

class DB_Connection
{
	private $_con = null;
 
    public static function getInstance()
    {
        static $instance=null;
        if ($instance === null)
            $instance = new DB_Connection();
        return $instance;
    }
 
    public function query($sql)
    {
    	// DO SOME CODE TO RUN A QUERY HERE
    }
 
    public function __destruct()
    {
    	$this->_con->close();
    }
 
    private function __construct()
    {
    	$this->_con = new DB::connect('connection_string');
    }
 
}
?>
You’re probably wondering why the class constructor is private. This seems odd as it’s impossible to create an object from outside the class, right? That’s the point. If we don’t limit the class instantiation, the singleton pattern is useless. The method getInstance() can create an object as it’s a member of that class.
How does the static method work?
The static method getInstance() declares a static variable called instance ($instance). The first time this method is called, the $instance variable’s value is null. We then check if the value is null — if it is, we create a new instance of DB_Connection — if it is not, we return the current instance.
Static variables work by declaring the static keyword, then continuing on with the normal variable initialization. The variable will maintain it’s assigned value (whether changed or not) throughout the life of the script.
The second time the getInstance() is called, the $instance variable contains the instance of DB_Connection, and we will return that value. Regardless of how many instances are created of this class, only one object is initialized.
Conclusion
As you can see, the singleton pattern certainly has it’s uses, albeit specific. Keeping the OOP design patterns in mind makes for a cleaner, easier to maintain code base for future developers picking up your projects.