Design Patterns: Singleton

The singleton design pattern is a way of enforcing only one instance of an object. This is achieved by making 3 fairly simple steps to a class. Firstly making the constructor private, creating a static member variable that will contain the instance and then creating a static method for accessing the instance.

So, In PHP it would be;

  1. class Foo {
  2.    
  3.     private static $instance = null;
  4.    
  5.     private function __construct(){
  6.         // Private, so can’t be accessed from outside
  7.     }
  8.    
  9.     private static function getInstance(){
  10.         if($this->instance == null) {
  11.             $this->instance = new Foo();
  12.         }
  13.         return $this->instance;
  14.     }
  15.    
  16.     public function bar(){
  17.         echo "I am one, I am a singleton!";
  18.     }
  19.    
  20. }
  21.  
  22. // Example usage
  23. $foo = Foo::getInstance();
  24. $foo->bar();
  25. // or the chaining method
  26. Foo::getInstance()->bar();
  27. // Note this will not work
  28. $myfoo = new Foo();

Why are singletons good? It’s almost like a global object right? What is good about a singleton as opposed to a concrete class? A concrete class has more flexibility as you can create multiple instances and then each instance can of course be different. However, what if you only ever want one instance of an object and ensure you don’t accidentally make another instance (or another developer doesn’t). You could use globals but they need to be managed somehow and people can still make mistakes and forget things.

The most common example is a database class, you might want to make sure that you only open one connection to the database. Creating multiple instances of database class could (depending how you programmed it) open multiple database connections and be inefficient.

The singleton can also be useful if an object that is used infrequently across a website. It can provide you easy access to it without having to worry about passing the object around. In the above code, you can access that object instance with this snippet of code “Foo::getInstance();”.

Tags: , ,

Leave a Reply