Implement Singleton Design Pattern in PHP

Last Updated: 21 Nov, 2023

Explain Singleton Design Pattern with Example

The Singleton Design Pattern falls under creational software design pattern which make sures that there must be only one instance of a class and ensures a single point of access to it. The meaning is if an instance of a class was already created, that existing instance will be returned and used instead of creating a new instance. The singleton design pattern is on of the well-known design patterns that solve the recurring design problems. It helps us how to design flexible and reusable object-oriented application with the aim of making it easier to implement, modify and test.

Points to note:

  • Define a public static method (getInstance()) that will return the sole instance of the class
  • The singleton pattern is responsible for ensuring that a class must be instanciated only once.
  • Then define a constructor (private or protected) which will make sure that the class can not be instantiated from the outside the class.
  • The public static method (getInstance()) can be accessed statically, e.g., Singleton.getInstance().

Provide some application usage of Singleton Design Pattern

Below are some application usage of Singleton Design Pattern:

  • When creating factory, abstract factory, method, builder and prototype patterns.
  • When we create Facade objects we often make use of singleton because only one facade object is required.
  • When creating State objects we often use singleton.
  • When creating global variables we often prefer singleton.

Basic Example:

<?php
class Singleton
{
    private static $instance = null;

    private function __construct() {}

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

        return self::$instance;
    }
}
?>

Example 2:

<?php
class DBConnection
{
    private static $instance = null;

    private final function __construct() {
        echo __CLASS__ . " initialize only once.<br>";
    }

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

        return self::$instance;
    }
}

//create an object of DBConnection class
$conn1 = DBConnection::getInstance();

//create anothe object of DBConnection class
$conn2 = DBConnection::getInstance();

var_dump($conn1 == $conn2);

/* OUTPUT
DBConnection initialize only once.
bool(true)
*/
?>

Example 3: making database connection and fetching records from it

<?php
class DBConnection
{
	private static $instance = null;
	public $db = null;

    private final function __construct() 
    {
    	try {
    		$connection = new PDO('mysql:host=your_host;dbname=your_db', 'your_username', 'your_password');
    		$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    		$this->db = $connection;
    	} catch (\PDOException $e) {
    		die($e->getMessage());
    	}
    }

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

		return self::$instance;
	}
}

class Product
{
	protected $db;

	public function __construct()
	{
		$this->db = DBConnection::getInstance()->db;
	}

	public function getProducts()
	{
		$products = [];
		$stmt = $this->db->prepare("SELECT * FROM products LIMIT 3");
		$stmt->execute();
		$result = $stmt->fetchAll();
		if (count($result) > 0) {
			foreach ($result as $row) {
				$products[] = array(
					'name' => $row['name'],
					'mrp' => $row['mrp'],
					'discount' => $row['discount'],
					'price' => $row['price']
				);
			}
		}
		return $products;
	}
}

//create an object of Product class
$p = new Product();
$products = $p->getProducts();
print_r($products);
?>

 

Thank You, Please Share.

Recommended Posts

PHP 7 New Features and Enhancements Explained

PHP 7 New Features and Enhancements Explained

In this easy and simplified tutorial, we are going to learn about most awaited PHP version (PHP 7) and its super important features and enhancements.

IMAGE

PHP OOP Interfaces Explained

An Interface allows you to create programs that specifies which methods a class must implement, without defining how those methods are implemented.

IMAGE

PHP OOP Abstract Classes Explained

A PHP class that has minimum one abstract method is called as abstract class and cannot be instantiated by itself.