by Dinesh Thakur

In most professional developments, it is necessary to know proper structure of their application in order to facilitate its design and maintenance. The "design patterns", is one of the best solutions to this problem. With the new model object-oriented PHP 5 similar to that of Java, the implementation of design patterns is facilitated. This tutorial focuses on the presentation and implementation of the Singleton pattern, especially used in web applications.

What is a design pattern?

In software engineering, a design pattern is a concept of designed to solve recurrent problems following the object paradigm.

The design patterns are solutions that address recurring problems of architecture and software design. It is neither algorithms or code fragments. The desing patterns describe general design processes regardless of the programming language used. This is also why we present the design grounds in the form of UML class diagram.

Clearly, design patterns must be seen as a design tool and formal structuring of computer applications. These are proven solutions and are among the good programming practices to adopt.

Introduction to the Singleton design pattern

Presentation Singleton design pattern

The Singleton object-oriented programming, answers to the problem of having a single instance of the same class in a program. For example, as part of a dynamic web application, the connection to the database server is unique. To preserve this uniqueness, it makes sense to use an object that takes the form of a singleton. So just for example to create the only representative object access to the database, and store the reference to it in a global variable so that the program can be accessed from anywhere in the script.

Structure of a singleton class

Specifically, a singleton is very simple to implement. It consists of three features:

• A private static attribute that retain the unique instance of the class.
• A private constructor to prevent the creation of items from outside the class
• A static method to either instantiate the class is to return the unique instance created.

The code below shows a minimal class that incorporates the Singleton design pattern. We find the minimum, namely the three characteristics presented just above.

Minimum Singleton Structure
<?php
   class Singleton {
     /**
       * @var Singleton
       * @access private
       * @static
       */
       private static $_instance = null;
    /**
      * Constructor Class
      *
      * @param void
      * @return void
      */
     private function __construct() {
     }
   /**
     * Method that creates the single instance of the class
     * If it does not yet exist back then.
     *
     * @param void
     * @return Singleton
     */
     public static function getInstance() {
        if(is_null(self::$_instance)) {
           self::$_instance = new Singleton();
        }
           return self::$_instance;
    }
}
?>

The variable $ _instance is declared as static. This is a class variable, that is to say, its value does not depend on the object created from this class. Thus, if two objects are from the same class, they can share the same variable and read the same value regardless of their status at time T. This $ _instance variable loads to keep the Singleton type of object that will be created. Thanks to the private builder and the getInstance () method, it is impossible to create several objects of type Singleton.

The constructor is declared private so they can not be called from outside the class. More concretely, it is thus impossible to make a "new" outside the classroom. The only way to get an instance of the class is to go through public static method getInstance ().

The getInstance () method must be public and static. The statement with the keyword "public" allows it to be called out of class. The keyword "static", meanwhile, allows it to be called without passing through the object (since we did not object when the call). The purpose of this method is to make access control. It first checks that the $ _instance static property is null or not. If it is NULL then it creates this variable in an instance of the same class. Then it returns that instance. This is the one and only instance that can you can do: it is the singleton.

Testing the class Singleton

To control our class is doing its job, we will first try to instantiate the class from outside and we will try to get two different instances of the class.

Attempt to instantiate from outside the class

<? php
    // Import Class
    require (dirname (__ FILE __) '/ Singleton.php.');
    // Attempt to class instantiation
         $ oSingleton = new Singleton ();
?>

Because of the declaration "private" constructor, we can not instantiate the class directly. PHP therefore generates a not surprising error.

Fatal error: Call to private Singleton :: __ construct () from invalid context in /Users/MySingleton.php on line 7

Tentative construction of two Singleton objects of type

<? php
   // Import Class
        require (dirname (__ FILE __) '/ Singleton.php.');
   // Attempt to class instantiation
        $ oSingletonA = Singleton :: getInstance ();
        $ oSingletonB = Singleton :: getInstance ();
        echo '<pre>';
        var_dump ($ oSingletonA);
        echo '</ pre>';
        echo '<pre>';
        var_dump ($ oSingletonB);
        echo '</ pre>';
?>

We get the following result:

     object (Singleton) # 1 (0) {
     }
     object (Singleton) # 1 (0) {
     }

The # 1 is the reference of the instance. Here we see that the two objects $ oSingletonA and $ oSingletonB, this reference is identical. We therefore concluded that these two variables reference (link) on the same object in memory. So we managed to create a unique instance of the class, the famous Singleton.

Singleton Implementation Example

As it stands, our Singleton class does not allow us to be usable in a concrete project. It is only the minimalist frame of an object adopting the form of a Singleton. We will build on a concrete example from reality to further illustrate this pattern.

As we all know, a single person is the head of our country. This is the President of the Republic. There can be more than one. So we can easily represent this constraint as a class incorporating the specificities of singleton.

<? php
   class PresidentOfTheRepublic {
    / **
       * The sole purpose PresidentOfTheRepublic
       *
       * var PresidentOfTheRepublic
       * Access Private
       * static
       * /
       private static $ _instance = null;
        / **
           * The name of the President
           *
           * var String
           * Access Private
           * /
            private $ _name = '';
        / **
           * The name of the President
           *
           * var String
           * Access Private
           * /
           private $ first_name = '';
         / **
            * Chained representation of the object
            *
            void * param
           *return String
         * /
         public function __toString () {
            return $ this-> getfirst_name (). ' '. strtoupper ($ this-> getName ());
         }
       / **
          * Class Constructor
          *
          *param String $ name Name of the President
          *param String $ firstname of the President
          *return Void
          * Private access
          * /
           private function __construct ($ name, $ first_name) {
              $ this -> _ name = $ name;
              $ this -> _ $ firstname = firstname;
           }
          / **
             * Method that creates the single instance of the class
             * If it does not yet exist back then.
             *
             *param String $ name Name of the President
             *param String $ firstname President of First
             *return PresidentOfTheRepublic
             * /
              public static function getInstance ($ name, $ first_name) {
                  if (is_null (self :: $ _ instance)) {
                      self :: $ _ instance = new PresidentOfTheRepublic ($ name, $ firstname);
                   }
              return self :: $ _ instance;
              }
           / **
              * Returns the name of the President
              *
              *return String
              * /
              public function getName () {
                     return $ this -> _name;
                 }
             / **
                * Returns the name of the President
                *
                *return String
                * /
                 public function firstname() {
                      return $ this -> _ firstname;
         }
}

?>
Object creation:

<? php
       // Import Class
           require (dirname (__ FILE __) '/ PresidentOfTheRepublic.php.');
      // Instantiation of the object
           $ oPresident = PresidentOfTheRepublic :: getInstance ('Narinder', 'Modi');
      // Implicit call to the __toString () method
           echo $ oPresident;
?>

We get good results following standard output:

Narinder Modi