Singleton design pattern in PHP - How to create and how to implement

Categories - Design Pattern in PHP Tags - Design pattern PHP   Maniruzzaman Akash   2 years ago   542   3 minutes   0

The Singleton design pattern is a popular software design pattern that is used to ensure that a class has only one instance and provides a global point of access to it. This pattern is useful when you want to make sure that only one instance of a class is created and used throughout your application.

In PHP, implementing the Singleton pattern is fairly simple. All you need to do is create a private constructor and a static method that returns an instance of the class. Here is an example of how you can implement the Singleton pattern in PHP:

<?php

class Singleton
{
    private static $instance;

    private function __construct()
    {
        // private constructor to prevent object creation
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}

$singleton1 = Singleton::getInstance();
$singleton2 = Singleton::getInstance();

if ($singleton1 === $singleton2) {
    echo 'Same instance';
}

In the code above, we have defined a class named Singleton that has a private constructor and a static method named getInstance(). The getInstance() method checks if an instance of the Singleton class already exists and returns it if it does. If no instance exists, it creates a new instance of the Singleton class and returns it.
One important thing to note is that the Singleton class has a private constructor. This means that objects of the Singleton class cannot be created using the new keyword. The only way to get an instance of the Singleton class is to use the getInstance() method. This ensures that only one instance of the Singleton class is created and used throughout the application.
In the example above, we have created two objects of the Singleton class using the getInstance() method. We have then checked if these two objects are the same instance or not. Since the Singleton class only allows one instance to be created, both the objects will be the same instance, and the code will print “Same instance” on the screen.
The Singleton pattern is useful when you want to make sure that only one instance of a class is created and used throughout your application. It is commonly used for implementing objects that manage resources, such as database connections or logger objects.

Practical Example

Here is another example of how the Singleton pattern can be used to create a logger object:

<?php

class Logger
{
    private static $instance;

    private function __construct()
    {
        // private constructor to prevent object creation
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new Logger();
        }
        return self::$instance;
    }

    public function log($message)
    {
        // code to log the message
    }
}

$logger1 = Logger::getInstance();
$logger1->log('Hello, world!');

$logger2 = Logger::getInstance();
$logger2->log('Hello, world again!');

In the code above, we have defined a Logger class that has a private constructor and a static method named

Pros:

  1. Ensures that only one instance of a class is created, which can be useful for maintaining global state.
  2. Can be useful for implementing resources that are expensive to create (e.g. database connections) as the singleton instance can be shared among different parts of the code.
  3. Can be useful for implementing a global logging system or a global configuration object.

Cons:

  1. Can make unit testing difficult as the singleton instance cannot be easily mocked or stubbed.
  2. Can make code less modular and less reusable as it tightly couples the code to the singleton instance.
  3. Can make code more difficult to understand and maintain as it introduces global state.
  4. Can lead to race conditions if not implemented correctly.