26 novembro 2010

Implementação da Pattern Singleton em PHP

Um artigo interessante e que demonstra como implementar a pattern Singleton em PHP. Neste artigo também está um exemplo de como usar esta mesma classe.
class SingletonClass
{
//A static member variable representing the class instance
private static $_instance = null;
//Locked down the constructor, therefore the class cannot be externally instantiated
private function __construct() { }
//Prevent any object or instance of that class to be cloned
public function __clone() {
trigger_error( "Cannot clone instance of Singleton pattern ...", E_USER_ERROR );
}
//Prevent any object or instance to be deserialized
public function __wakeup() {
trigger_error('Cannot deserialize instance of Singleton pattern ...', E_USER_ERROR );
}
//Have a single globally accessible static method
public static function getInstance()
{
if( !is_object(self::$_instance) )
//or if( is_null(self::$_instance) ) or if( self::$_instance == null )
self::$_instance = new self;
//or, in PHP 5.3.0
//if (empty(static::$_instance)) {
// $class = get_called_class();
// static::$_instance = new $class;
//}
return self::$_instance;
}
}
Artigo Completo

Sem comentários: