Singleton design pattern in PHP, Learn design patterns

This article with guide you through the singleton pattern in PHP, with theory explanation, and the practical example as well. Singleton design pattern is one of the first design patterns that is explained in any design patterns book or tutorial.

Singleton Design Pattern in PHP

Nature wise, singleton pattern belongs to the category of creational design patterns. Patterns from this category are:

Firstly, the singleton design pattern is used when we want to ensure that only one object of the class can be created.

A short reminder on object oriented concepts.

So, in general, one class can be instanced lots of times. Meaning, we can create multiple objects from one class. However, sometimes we need to ensure that multiple objects can not be created.

Secondly, patterns will never provide us with an actual code, only with a concept. Actual codes that we find online can be proposed by developers or anyone else who actually implemented one pattern.

Sign up for my newsletter because you want to get some quality content served right into your mailbox. Give it a try, it is a great way to improve your development and business skills. Just like a warm cup of tea in the evening, it will do good for you. Even better, you will get the latest news, updates, and promotions. No tea included. 🙂

Note: Your information is protected and I never spam, ever. You can view my privacy policy here.

The concept

Classes themselves can not “deny” the creation of objects. We need to write some code to make this happen. The singleton pattern describes a way on how to accomplish this.

This is a general idea when implementing the singleton pattern.

  1. Firstly, we want to make a dedicated class that can produce only one object.
  2. Secondly, we want to make the constructor of this class private, so that this class can not be called from the outside.
  3. Thirdly, we want to create any kind of public function for fetching instances of objects.
  4. Then, we implement a logic that checks if the object already exists or not, in function for object fetching.
  5. Finally, we write a logic that will create an object if it does not already exist. This is called the first time creation. However, if the object already exists then our logic will use the existing object.

The singleton pattern – PHP implementation

Here is a simple and quick example of a singleton design pattern in PHP.

You can find the latest version of this code in the design patterns code repository.

<?php

/*
 * We will create a class called "Singleton".
 * In a real use case, this class would have a different name.
 */
 class Singleton {
    
    /* We define singleton instance object as static, 
     * so it can be accessed without instancing class.
     */
    private static $singletonInstance = null;
    
    /* 
     * In the case of singleton, we want to have constructor private
     * to prevent some other part of the code from executing it.
     * 
     * Since singleton class should be instanced only once, we don't want 
     * Other parts of the code having the possibility to instance it.
     */
    private function __construct()
    {
      /* 
       * Actual logic of the singleton class.
       * i.e. if we have database connection singaleton class, 
       * then the connection logic goes here.
       */
    }
   
    /**
     * Function which checks if the object of this class already exists.
     * If not, then the object is created (first and the only time).
     * If the object already exists, a new one will not be created.
     * 
     * @return object Singleton instance object
     */
    public static function getInstance()
    {
      if (self::$singletonInstance == null) {
          echo "New instance of class is created. \n";
        self::$singletonInstance = new Singleton();
      } else {
          echo "Instance already exist, new instance WILL NOT be created. \n";
      }
   
      return self::$singletonInstance;
    }
}

// Then, for example, we would use this object several times in different places.

$object1 = Singleton::getInstance();
$object2 = Singleton::getInstance();
$object3 = Singleton::getInstance();
$object4 = Singleton::getInstance();
$object5 = Singleton::getInstance();

When should we use the singleton pattern?

Lots of online blogs, tutorials, and code junkies state that singleton is just a glorified global variable. This makes no sense and it is just plain wrong.

Singleton classes are not just another way of wrapping global variables. The idea behind singleton is to make an expensive part of the logic (i.e. database connection or log system connection) happening only once and then reused.

Of course, this approach can not and will not solve all coding problems. As with every pattern, there are cases when singleton should and can be used, and when singleton can not and should not be used.

Having that in mind, misusing singleton can and will cause a lots of potential issues.

This is my opinion on how and when singleton should be used:

  • This pattern should be utilized carefully, meaning in minimum amount of cases and only when we are sure what we want to accomplish.
  • For code logic that is “expensive” and that should not logically be instances multiple times. One common example for this one is “database connectivity class” but again, this depends of our use case.

Singleton as anti pattern

“Anti pattern” means that something is coded or used in the way that is commonly known to be bad.

Meaning, anti-pattern represents common use cases that were recognized as bad implementation or potential issues with using some pattern.

Anti pattern considerations for singleton:

  • It is very complex to unit test code with singleton patterns.
  • We can not be sure of all things influencing an object.
  • Possible caching challenges. I.e. we are caching something for one process, which is shared among different processes. Meaning, we are possibly breaking state dependencies.

References

Read up on the interesting discussion on creating this design pattern in php5

If you are interested in how to implement this pattern in Java take a look at this example. Also, if you want to know how singleton looks like in Python check out this post.