How would one create a Singleton class using PHP5 classes?
PHP 5.3 allows the creation of an inheritable Singleton class via late static binding:
class Singleton
{
protected static $instance = null;
protected function __construct()
{
//Thou shalt not construct that which is unconstructable!
}
protected function __clone()
{
//Me not like clones! Me smash clones!
}
public static function getInstance()
{
if (!isset(static::$instance)) {
static::$instance = new static;
}
return static::$instance;
}
}
This solves the problem, that prior to PHP 5.3 any class that extended a Singleton would produce an instance of its parent class instead of its own.
Now you can do:
class Foobar extends Singleton {};
$foo = Foobar::getInstance();
And $foo will be an instance of Foobar instead of an instance of Singleton.
I agree with the first answer but I would also declare the class as final so that it cannot be extended as extending a singleton violates the singleton pattern. Also the instance variable should be private so that it cannot be accessed directly. Also make the __clone method private so that you cannot clone the singleton object.
Below is some example code.
/**
* Singleton class
*
*/
final class UserFactory
{
private static $_instance = null;
/**
* Private constructor
*
*/
private function __construct() {}
/**
* Private clone method
*
*/
private function __clone() {}
/**
* Call this method to get singleton
*
* @return UserFactory
*/
public static function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new UserFactory();
}
return self::$_instance;
}
}
Example Usage
$user_factory = UserFactory::getInstance();
What this stops you from doing (which would violate the singleton pattern..
YOU CANNOT DO THIS!
$user_factory = UserFactory::$_instance;
class SecondUserFactory extends UserFactory { }
You probably should add a private __clone() method to disallow cloning of an instance.
private function __clone() {}
If you don't include this method the following gets possible
$inst1=UserFactory::Instance(); // to stick with the example provided above
$inst2=clone $inst1;
now $inst1
!== $inst2
- they are not the same instance any more.
protected static $_instance;
public static function getInstance()
{
if(is_null(self::$_instance))
{
self::$_instance = new self();
}
return self::$_instance;
}
This code can apply for any class without caring about its class name.
This method will enforce singletons on any class you wish, al you have to do is add 1 method to the class you wish to make a singleton and this will do it for you.
This also stores objects in a "SingleTonBase" class so you can debug all your objects that you have used in your system by recursing the SingleTonBase
objects.
Create a file called SingletonBase.php and include it in root of your script!
The code is
abstract class SingletonBase
{
private static $storage = array();
public static function Singleton($class)
{
if(in_array($class,self::$storage))
{
return self::$storage[$class];
}
return self::$storage[$class] = new $class();
}
public static function storage()
{
return self::$storage;
}
}
Then for any class you want to make a singleton just add this small single method.
public static function Singleton()
{
return SingletonBase::Singleton(get_class());
}
Here is a small example:
include 'libraries/SingletonBase.resource.php';
class Database
{
//Add that singleton function.
public static function Singleton()
{
return SingletonBase::Singleton(get_class());
}
public function run()
{
echo 'running...';
}
}
$Database = Database::Singleton();
$Database->run();
And you can just add this singleton function in any class you have and it will only create 1 instance per class.
NOTE: You should always make the __construct private to eliminate the use of new Class(); instantiations.
Database class that checks if there is any existing database instance it will return previous instance.
class Database {
public static $instance;
public static function getInstance(){
if(!isset(Database::$instance) ) {
Database::$instance = new Database();
}
return Database::$instance;
}
private function __cunstruct() {
/* private and cant create multiple objects */
}
public function getQuery(){
return "Test Query Data";
}
}
$dbObj = Database::getInstance();
$dbObj2 = Database::getInstance();
var_dump($dbObj);
var_dump($dbObj2);
/*
After execution you will get following output:
object(Database)[1]
object(Database)[1]
*/
Ref http://www.phptechi.com/php-singleton-design-patterns-example.html