PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

Single instance

Singleton pattern restricts the instantiation of a class to a single instance. Private keyword hides the class constructor for outside.
 
class MyClass
{
   private static $instance;

   public $userId;

   /**
    * Private constructor
    * The class cannot be intialized from outside
    */
   private function __construct() {}

   /**
    * Static methods or properties can be access
    * only as part of a class itself
    */
   public static function  getInstance()
   {
       if (self::$instance === null) {
           self::$instance = new self(); // Look Here
       }
       return self::$instance;
   }
}

// $obj = new MyClass(); // Fatal Error

$obj = MyClass::getInstance();
$obj->userId = 2;

$obj2 = MyClass::getInstance();
echo $obj->userId; // 2
... 21 lines
 

Example

Prevent class from being extended, declare it as final. Prevent second instance of the class (private _clone() or __wake()).
 
// App.php

declare(strict_types=1);

namespace DesignPatterns\Singleton;

final class App
{
   private static $instance;

   /**
    * get the instance via lazy initialization
    * intialization created on first usage
    */
   public static function  getInstance() : App
   {
       if (! static::$instance) {
           static::$instance = new self();
       }

       return static::$instance;
   }

   /**
    * prevent outside multiple instantiantion
    * getInstance() must be used instead
    */
   private function __construct()
   {
   }

   /**
    * prevent the instance from being clone
    * which will create a second instance of it
    */
   private function __clone()
   {
   }

   /**
    * prevent the instance from being unserialized
    * which will create a second instance of it
    */
   private function __wakeup()
   {
   }
}
... 34 lines
 
 
// index.php

namespace DesignPatterns\Singleton;

require_once __DIR__ . "/../../autoloader.php";

use DesignPatterns\Singleton\App;

$A = App::getInstance();
$B = App::getInstance();

echo $A instanceof App; // true
echo $B instanceof App; // true
... 3 lines
 
 
// autoloader.php

function classAutoloader($class) {

    $tmp = explode("\\", $class);
    require_once join("/", $tmp) . ".php";
}

spl_autoload_register("classAutoloader");
... 1 lines
 

Questions    
Observer Pattern

        A B C D E F
🔔
1/1