আগামী ২৩ অক্টোবর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML,CSS,Bootstrap,PHP,MySQl, AJAX and JQUERY কোর্সের ৮৬ তম ব্যাচ। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722817591, Email : [email protected] কোর্সের সিলেবাস এর জন্য এখানে ক্লিক করুন ।

Singleton Design Pattern in PHP

Singleton Design Pattern in PHP

The Singleton ensures that there can be only one instance of a Class and provides a global access point to that instance. Singleton is a “Gang of Four” Creational Pattern.

The Singleton pattern is often implemented in Database Classes, Loggers, Front Controllers or Request and Response objects.

Singleton: problem & solution

Problem

Solution

  • You want a class to have exactly one instance
  • You want the instance to be easily accessible
  • You don’t want to use global variables
  • The Singleton pattern ensures a class has only one instance, and provide a global point to access it

Singleton: considerations

  • Often used for shared objects such as configurations, queues, database connections…
  • You don’t want the environment to be responsible of class instantiation
  • You don’t want the environment to be responsible of avoid multiple class instances
  • The Singleton is often a mixed behavior

Singleton: Class as Singleton

  • You can declare methods as static and use the class as the container for the Singleton functionality
  • You are sure no one will create additional instances
  • You can’t take advantage of other patterns, such as Lazy Initialization
  • You don’t have control over initialization
  • You don’t have access to the instance context
  • It’s not thread safe

Singleton: Why not using Global Variables?

  • There’s no way to control the value of a global variable
  • Doesn’t prevent someone from creating multiple instances
  • Global variables are unpredictable
  • Global variables are difficult to debug and test
  • Global variables are unsecured
  • Global variable makes the code difficult to read

Singleton: using & abusing

  • Before applying a Singleton ask yourself: do I really need a Singleton?
  • Look at your code, check the number of a class instances
  • Beware to not spread the Singleton knowledge in classes where you don’t really need to
  • To all intents and purposes, a Singleton instance is a normal class instance, you can pass it as a parameter

Real Life Example

Imagine a class of 4 students. Each student has one responsibility when the class starts – he/she must shout out loud his/her name for their teacher to write down in his attendance book.

Below is some sample code that implements the described task in the conventional way. Two classes are declared – Teacher and Student. The Teacher class has one protected property $_name and two public methods – one is the constructor and the other one marks a student as present. There is also another property $_number_of_instances which is static and it is just for the sake of keeping track of how many instances of the class are created.

The Student class has two properties – the name of the student and the student’s teacher. Naturally, it has one public constructor and a public method shoutYourName that needs to tell the teacher that the student is present.

One thing to notice is that every time a student object is instantiated, a brand new teacher object is created as well. In other words, every student in this class has his/her own teacher. Going further down the sample code, four students are created and then they inform their teacher(s) of their presence.

<?php
  /**
  Example of conventional  implementation
  */
  class Teacher {
  private $_name;
  static  $_number_of_instances = 0;
  public function  __construct() {
  //initialise the  object
  $this->_name =  'James Hetfield';
  self::$_number_of_instances ++;
  echo 'number of  teachers:' . self::$_number_of_instances . '<br/>';
  }
  public function  takeAttendance($studentName) {
  //mark the student  as present (insert to database)
  echo $studentName  . 'is present.<br/>';
  }
  }
  class Student{
  private $_name;
  private $_teacher;  //the teacher of the student
  public function  __construct($name) {
  //create a student
  $this->_name =  $name;
  $this->_teacher  = new Teacher();
  }
  public function  shoutYourName(){
  $this->_teacher->takeAttendance($this->_name);
  }
  }
  $kirk = new Student('Kirk');
  $lars = new Student('Lars');
  $robert = new Student('Robert');
  $jason = new Student('Jason');
  $kirk->shoutYourName();
  $lars->shoutYourName();
  $robert->shoutYourName();
  $jason->shoutYourName();
  ?>
  

Output:
number of teachers:1
number of teachers:2
number of teachers:3
number of teachers:4
Kirk is present.
Lars is present.
Robert is present.
Jason is present.

The picture below illustrates the result of the conventional implementation. It creates multiple unnecessary objects that do the same thing essentially (moreover, it does not recreate the described plot of 4 students and only 1 teacher).

Example for PHP Singleton Design Pattern

This is where the Singleton pattern comes into play. Below you can see a rewrite of the sample code. The Teacher class has been modified to become a, what is called, Singleton class. The modifications are as follows:

  • Another static property has been added $_instance that will hold the self-created instance of the class.
  • The constructor method was changed from public to private, restricting its access from the outside.
  • A private method __clone() has been declared (doing nothing) to overwrite the PHP magic method __clone() in order to prevent object cloning
  • A public static method getInstance() has been created. Its function is to check if there is already an instance of the class, if there is not it creates one, stores it in the static $_instance variable and finally returns it to whoever requested it.
  • The Student object gets a reference to the teacher’s instance by calling the Teacher::getInstance method.
<?php
/**
Example of Singleton Pattern implementation
*/
class Teacher {
private $_name;
static $_instance;
static $_number_of_instances = 0;
private function  __construct() {
//initialise the object
$this->_name = 'James Hetfield';
self::$_number_of_instances ++;
echo 'number of teachers:' . self::$_number_of_instances .'<br/>';
}
private function  __clone() {
//do nothing (this overwrites the special PHP method __clone())
}
public static function getInstance() {
if(!(self::$_instance instanceof self)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function takeAttendance($studentName) {
//mark the student as present (insert to database)
echo $studentName . ' is present.<br/>';
}
}
class Student{
private $_name;
private $_teacher; //the teacher of the student
public function  __construct($name) {
//create a student
$this->_name = $name;
$this->_teacher = Teacher::getInstance();
}
public function shoutYourName(){
$this->_teacher->takeAttendance($this->_name);
}
}
$kirk = new Student('Kirk');
$lars = new Student('Lars');
$robert = new Student('Robert');
$jason = new Student('Jason');
$kirk->shoutYourName();
$lars->shoutYourName();
$robert->shoutYourName();
$jason->shoutYourName();
?>

The code outputs the following:

Number of teachers:1
Kirk is present.
Lars is present.
Robert is present.
Jason is present.

The picture below shows the result. As you can see, using the Singleton pattern, the Teacher class has been instantiated just once and then each Student object receives a reference of that instance.

PHP Singleton Example

Benefits of the Singleton Pattern

The Singleton pattern prevents memory duplication and, therefore, saves system resources. In addition, using the Singleton pattern, you can be sure that there is only one flow path for a certain task or data. This results in more controlled and secure application work flow as well as easier debugging and maintenance.

PHP Single ton Design pattern

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor's degree in Engineering from State University Of Bangladesh, I'm also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i'm a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I'm also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute - a leading Training Institute in the country.