Singleton Design pattern in PHP

 Hi Folks,

Today I will explain about Singleton Design pattern in php.


 

What is Singleton Pattern?

In Singleton Design Pattern, we ensure a class has only one and only one instance and that instance can be accessed globally. The Singleton design pattern restricts the instantiation of a class to one object.

  • Singleton can be used like a global variable.
  • It can have only one instance (object) of that class unlike normal class.
  • When we don't want to create a more than one instance of a class like database connection or utility library we would go for singleton pattern.
  • Singleton makes sure you would never have more than one instance of a class.
  • Make a construct method private to make a class Singleton.
  • If you don't want to instantiate a multiple copies of class but only one then you just put it in singleton pattern and you can just call methods of that class and that class will have only one copy of it in a memory even if you create another instance of it.
  • If user just wants to connect to database then no need to create a another instance again if the instance already exist, you can just consume first object and make the connection happen.

How to Create Singleton Class in PHP?

 To create a Singleton class we need

  1. Static member variable – It acts as a placeholder for the instance of that class
  2. Private Constructor – Private constructor prevents direct instantiation of a class.
  3. Prevent object cloning by making clone Magic Method private.
  4. Create a static method for global access.    

Eg:

<?php
    class DBConn {

        private static $obj;

        private final function  __construct() {
            echo __CLASS__ . " initializes only once\n";
        }

        public static function getConn() {
            if(!isset(self::$obj)) {
                self::$obj = new DBConn();
            }
            return self::$obj;
        }
    }

    $obj1 = DBConn::getConn();
    $obj2 = DBConn::getConn();

    var_dump($obj1 == $obj2);
?>


Output:

DBConn initializes only once
bool(true)

Object1 and Object2 will point to the same instance

            _______________________
           |                       |
$obj1 ---->|  Instance of DBConn   |<----- $obj2
           |_______________________| 


Comments