PHP Singleton Pattern

In programming, patterns are like little recipes that solve common problems.

My favourite pattern is the Singleton pattern. I like it because it is incredibly simple to use and incredibly useful.

Let's say that you have some kind of configuration file for your application that you want to load once and be able to access everywhere.

A nice way of solving this, is by having a wrapper class that holds the configuration and making is static so that it only loads the configuration once.

Let's start with a basic class:

class Configuration
{
    private $config;
    private static $instance = null;

    private function __construct()
    {
    }
}

Inside the class, I have two properties:

  • $config which will hold an array of the settings.
  • $instance which will hold the current instance of the class. This is initialised to null which indicates that it has not previously been created.

I have also created the constructor. You will notice that this is private. This is to prevent the class from being instantiated outside of the class. Remember, we only ever want it to be instantiated once and so that is controlled from within the class.

Inside the constructor we might have some call to some function that magically loads some config file. I am abstracting away the details of that for the purposes of this demo.

Now we add good bit:

class Configuration
{
    private $config;
    private static $instance = null;

    private function __construct()
    {
         $config = loadSomeConfig();
    }

    public static getInstance()
    {
         if (is_null(self::$instance)) {
              self::$instance = new Configuration;
         }
         return self::$instance;
    }
}

So I have added a new static function called getInstance. It simply checks if $instance has previously been instantiated or not. If not, it would still be null and it does the instantiation before returning it. If it has, it would simply return it.

The result is that anywhere in your code, you would do a call like this:

$myConfig = Configuration::getInstance();

This would either create the object if it is the first time it is called or simply return the previously created one.

A big benefit of this pattern is that you don't have to manually check all over the code whether this object is created or not every time you want to use it (and if you are too lazy for the check, avoid creating it every single time).

For things like a database connection or reading a file, this can really help save time and manage resources by only doing things once and centrally.


© 2012-2017