Singletons and Registry
Posted: Tue Nov 22, 2005 1:53 pm
Ok, I'm having a lot of troubles understanding how to implement a singleton pattern since it is vaguely documented..
Anyways over at http://www.phppatterns.com/docs/design/the_registry
and
Can anyone point me in the right direction on how to maintain a single instance of any particular class through my whole application?
Lets use my httpRequest class as an example.. from what I've gotten out of it all I have to do is extend the singleton and call $this->singleton() in the constructor to input the instance into cache.. apparantly that's not right?
Code: Select all
class Singleton
{
function Singleton() {
$registry = &Registry::instance();
if ($registry->isEntry('singleton ' . get_class($this))) {
trigger_error(
'Already an instance of singleton ' .
get_class($this));
}
}
function &instance($class) {
$registry = &Registry::instance();
if (!$registry->isEntry('singleton ' . $class)) {
$registry->setEntry(
'singleton ' . $class, new $class());
}
return $registry->getEntry('singleton ' . $class);
}
}Code: Select all
class Registry
{
var $_cache;
function Registry() {
$this->_cache = array();
}
function setEntry($key, &$item) {
$this->_cache[$key] = &$item;
}
function &getEntry($key) {
return $this->_cache[$key];
}
function isEntry($key) {
return ($this->getEntry($key) !== null);
}
function &instance() {
static $registry;
if (!$registry) {
$registry = new Registry();
}
return $registry;
}
}Lets use my httpRequest class as an example.. from what I've gotten out of it all I have to do is extend the singleton and call $this->singleton() in the constructor to input the instance into cache.. apparantly that's not right?
Code: Select all
class httpRequest extends Singleton
{
var $post = array();
var $get = array();
var $cookie = array();
function httpRequest() {
$this->Singleton();
$this->get = Sanitizer::sanitize($_GET);
$this->post = Sanitizer::sanitize($_POST);
$this->cookie = Sanitizer::sanitize($_COOKIE);
}