Singleton and Registry Help
Posted: Fri Feb 03, 2006 6:28 pm
Okay.. I've been using registry for awhile but I recently noticed that my singleton was not acting like a singleton at all.. there is obviously something I am missing.. but I cannot find much helpful documentation on this.. :\
Heres the code I'm using
Anways, I did a quick test to see if the instance was being saved, which is wasn't
outputs
Somethings that I realized is, when does the singleton's constructor get called, since I only should be calling this class statically, correct?
When and where do the methods $registry->save() and $registry->restore() actually get called?
Heres the code I'm using
Code: Select all
class Registry
{
var $_cache_stack;
function Registry() {
$this->_cache_stack = array(array());
}
function setEntry($key, &$item) {
$this->_cache_stack[0][$key] = &$item;
}
function &getEntry($key) {
return $this->_cache_stack[0][$key];
}
function isEntry($key) {
return ($this->getEntry($key) !== null);
}
function &instance() {
static $registry = false;
if (!$registry) {
$registry = new Registry();
}
return $registry;
}
function save() {
array_unshift($this->_cache_stack, array());
if (!count($this->_cache_stack)) {
trigger_error('Registry lost');
}
}
function restore() {
array_shift($this->_cache_stack);
}
}
class Singleton
{
function Singleton() {
$registry = &Registry::instance();
if ($registry->isEntry('singleton ' . get_class($this))) {
trigger_error(
'Already an instance of singleton ' .
get_class($this));
}
echo 'testing';
}
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 testRegistry
{
var $_input;
}
$testReg = Singleton::instance('testRegistry');
$testReg->_input = 'snap1';
$testReg = Singleton::instance('testRegistry');
print_r($testReg); #failed
$testReg->_input = 'snap2';
print_r($testReg); #ok
class testRegMethod
{
function testRegMethod() {
$testReg = Singleton::instance('testRegistry');
print_r($testReg); #failed
$testReg->_input = 'snap3';
print_r($testReg); #ok
}
}
$testRegMethod = new testRegMethod();
$testReg = Singleton::instance('testRegistry');
print_r($testReg); #failedCode: Select all
testregistry Object
(
[_input] =>
)
testregistry Object
(
[_input] => snap2
)
testregistry Object
(
[_input] =>
)
testregistry Object
(
[_input] => snap3
)
testregistry Object
(
[_input] =>
)When and where do the methods $registry->save() and $registry->restore() actually get called?