PHP - The Singleton Pattern

by Janeth Kent Date: 04-02-2022 pattern php singleton classes oop objects


The Singleton Pattern is one of the GoF (Gang of Four) Patterns. This particular pattern provides a method for limiting the number of instances of an object to just one. It's an easy pattern to grasp once you get past the strange syntax used.

Consider the following class:

PHP Code:

class Database { 
public function __construct() { ... }     
public function connect() { ... }    
public function query() { ... }  
...     
} 

This class creates a connection to our database. Any time we need a connection we create an instance of the class, such as:

PHP Code:

$pDatabase = new Database(); 
$aResult = $pDatabase->query('...');  

Lets say we use the above method many times during a script's lifetime, each time we create an instance we're creating a new Database object (we're also creating a new database connection, but that's irrelevant in this example) and thus using more memory. Sometimes you may intentionally want to have multiple instances of a class but in this case we don't.

The Singleton method is a solution to this common problem. To make the Database class a Singleton we first need to add a new property to the class, we'll call this $m_pInstance:

PHP Code:

class Database {
// Store the single instance of Database
private static $m_pInstance;
...
}

As the comment states, this property will be used to store the single instance of our Database class. You should also note that this property must be static.

Next we need to change the constructor's scope to private. This is one of the strange syntaxes that usually confuse people.

PHP Code:

class Database{
  // Store the single instance of Database
  private static $m_pInstance;
  private function __construct() { ... }
}

By making the constructor private we have prohibited objects of the class from being instantiated from outside the class. So for example the following no longer works outside the class:

PHP Code:

$pDatabase = new Database();  

We now need to add a method for creating and returning our Singleton. Add the following method to the Database class:

PHP Code:

public static function getInstance(){
  if (!self::$m_pInstance){
   self::$m_pInstance = new Database();
  }
  return self::$m_pInstance;
} 

This funny looking function is responsible for handling our object instance. It's relatively easy to understand, basically we check our static property $m_pInstance, if it is not valid we create a new instance of the Database class by calling the constructor. Remember, we made the __construct() method private, so an instance of the object can only be created from within the class' methods. Finally the function returns a reference to our static property. On subsequent calls to getInstance(), $m_pInstance will be valid and thus the reference will be returned - no new instances are created.

So our Database class now looks something like this

PHP Code:

class Database{
  // Store the single instance of Database
  private static $m_pInstance;     
  private function __construct() { ... }
  public static function getInstance(){ 
    if (!self::$m_pInstance){   
      self::$m_pInstance = new Database();     
    }
    return self::$m_pInstance;     
  }     
} 

You can now get an instance of the Database class from anywhere (without using globals or function arguments) in your project. Here's an example and comparison:

This is the usual way we create objects:
PHP Code:

$pDatabase = new Database(); 
$aResult = $pDatabase->query('...'); 

This is the Singleton way:
PHP Code:

$pDatabase = Database::getInstance();
$aResult = $pDatabase->query('...');   

  
To conclude, the Singleton is an easy-to-use design pattern for limiting the number of instances of an object.

 
by Janeth Kent Date: 04-02-2022 pattern php singleton classes oop objects hits : 2207  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

How to Send Email from an HTML Contact Form

In today’s article we will write about how to make a working form that upon hitting that submit button will be functional and send the email (to you as a…

The State of PHP 8: new features and changes

PHP 8.0 has been released last November 26: let's discover together the main innovations that the new version introduces in this language. PHP is one of the most popular programming languages…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The most popular Array Sorting Algorithms In PHP

There are many ways to sort an array in PHP, the easiest being to use the sort() function built into PHP. This sort function is quick but has it's limitations,…

The concept of Model-View-Controller (MVC) explained

In software engineering, we use design patterns as reusable solutions to a commonly occurring problem, a pattern is like a template for how to solve a problem. Model-View-Controller (MVC)  is a…

MySQL 8.0 is now fully supported in PHP 7.4

MySQL and PHP is a love story that started long time ago. However the love story with MySQL 8.0 was a bit slower to start… but don’t worry it rules…

Java Design Pattern: Builder Pattern

Today we are going to talk about a creational pattern that in many situations can represent a useful alternative to the construction of the objects using the constructors: the Builder…

Java Design Pattern: Strategy Pattern

One of the most popular patterns is the Strategy Pattern. It is also one of the easiest patterns. It is a member of the behavioral patterns family, it has the duty…

Java Design Pattern: Factory Method Pattern

Going on with the speach about design patterns started previously, we are going to talk about another pattern often used: the Factory Method Pattern. The GoF (Gang of Four Design Patterns)…

Java: introduction to Design Patterns and Singleton Pattern

Anyone with even a minimum experience of programming, should have realized that the majority of the problems have common elements. In fact we often find problems with the same pattern…

Javascript: Introduction to ES6 classes

An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and…

A roadmap to becoming a web developer in 2019

There are plenty of tutorials online, which won't cost you a cent. If you are sufficiently self-driven and interested, you have no difficulty training yourself. The point to learn coding…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration