Singleton Design Pattern is a Creational Pattern.

Goal Of The Singleton Pattern

  • Ensure a class has only one instance and provide a global point to retrieve it.
  • The singleton is used to create only one single point of entry or functionality within a system or application.
  • The purpose of the singleton pattern is to have just one single instance of an object in the entire application.

Possible Usage Of Singleton Pattern

  • When creating a database layer – you would want one instance to communicate with your database. Thus helping in maintaining only one connection instance instead of multiple one which might otherwise be resource consuming.
  • When you have a big/complex system going on; singleton helps in maintaining a synchronized state within your system. For example logged in a application make a great deal use of singleton within their respective application.
  • When you observe that most of the methods you are accessing within your projects, come from one recurring object. This is a candidate for being a singleton.

Anatomy Of A Singleton Pattern In A PHP

You need to have these conditions fulfilled:

  • A static member variable/ properties – as a properties for the instance of that class
  • Locked down the constructor of that class – simply by making it’s visibility private
  • Prevent any object or instance of that class to be cloned, that is to prevent any entity within the system to make copy of this object – make it visibility private.
  • Have a single globally accessible static method to access/retrieve the instance of that class – a public static method

Let’s implement all these things into codes :

<?php

class MyTestSingleton {

///Condition 1 - Presence of a static member variable
private static $_instance = null;
///Condition 2 - Locked down the constructor
private function __construct() {} //Prevent any oustide instantiation of this class
///Condition 3 - Prevent any object or instance of that class to be cloned
private function __clone() {} //Prevent any copy of this object

///Condition 4 - Have a single globally accessible static method 13.
public static function getInstance() {
if(self::$_instance == null){
self::$_instance = new MyTestSingleton();
echo "For first time enter this block at same session or same execution time
";
}
return self::$_instance;
}
///Now we are all done, we can now proceed to have any other method logic we want

public function getHello(){
echo "
Hello, This method is called by using a singleton object/Instance";
}
}

///Testing some calls to that class
$obj1 = MyTestSingleton::getInstance();
$obj1->getHello();
$obj2 = MyTestSingleton::getInstance();
$obj2->getHello();
$obj3 = MyTestSingleton::getInstance();
$obj3->getHello();
$obj4 = MyTestSingleton::getInstance();
$obj4->getHello();

I believe, Singleton is very useful design pattern.

Advertisements