The Singleton Pattern in PHP

The Singleton Pattern is considered a coding pattern for object-oriented applications.

The idea is relatively simple. A single object that can be used across multiple areas of the application, without being global.

Let's dig into it with some examples. We'll keep things simple.

The Boilerplate

A simple standard way of creating a singleton is as follows:

<?php
class MySingleton
{
    // Holds the object unless it hasn't yet been initialised
    private static $instance = null;

    private function __construct()
    {
        // The constructor is only called once.
        // The object cannot be initialise anywhere except within the class itself.
    }

    // Gets the instance
    public static function instance() : MySingleton
    {
        if(self::$instance === null)
            self::$instance = new MySingleton();

        return self::$instance;
    }
}

Instead of directly instantiating MySingleton, we simply call the static function instance() which will return a MySingleton instance or create one if it hasn't yet been created.

By making __constuct() private, we prevent the class being instantiated except from a method within the class itself. This way we are trying to prevent multiple instances from being created.

$myInstance = new MySingleton(); // Fatal Error
$myInstance = MySingleton::instance(); // Correct way

The purpose

We can now access the MySingleton access with ease from anywhere within our code base without worrying about what variable it is stored under and whether we can access the variable.

The Risks

Fortunately (unless you are explicitly using a multitask library), PHP is single threaded, so we don't need to worry about thread safety.

But we need to be aware that the state of the object can change which can cause issues if you are not careful.

An example would be using a Singleton as a database connection handler. You might expect the connection to be active but another method may have closed the connection, causing random errors to occur if not handled correctly.

Conclusion

Singletons have their purpose but they must be used carefully. Don't overuse them and consider the consequences of what they do. And beyond all, make sure you are handling changes in state correctly.

Written by Kieran on 2019-08-11
This website uses Cookies to enhance your experience. Close Manage