Monday, 30 July 2012

PHP Simple Singleton

Here's a nice little trait(the new type of construct in PHP 5.4) to allow you to take a class and turn it into a singleton

Here we go: 
1) Include the trait 
2) Change the constructor to protected 
.. and that's it. Happy days


namespace test;

class boosh
{ use \system\mixin\_Singleton;
 protected function __construct() 
 { }

$mighty = boosh::getInstance();

The Singleton Source

namespace system\mixin;

trait _Singleton
 private static $obj;
  * @brief  Using a singleton pattern to return a reference of the base class 
  * @return a reference to a shared instance
 final public static function getInstance()
  $lastClass = get_called_class();
  if(false == isset(self::$obj))
   self::$obj = new static();
  return self::$obj;
So what's the key? The secret is in static. Using "new static();we are getting a reference to the class that the developer is invoking this against. 
Not the class that the function is defined in. :D

Short and Sweet!
... continue reading!