[Typo3-dev] singletons instead of pre-loaded objects
Martin T. Kutschker
Martin-no5pam-Kutschker at blackbox.n0spam.net
Tue Aug 10 01:04:50 CEST 2004
Robert Lemke wrote:
> On Mon, 2004-08-09 at 20:47, Martin T. Kutschker wrote:
>
>>Why? You need some place to store the object references. As options I
>>see either a global array, a master object known to be loaded or factory
>>objects for every singleton (the object has a method with a static var
>>as storage).
>
> Because the recommended way for implementing the Singleton pattern is
> not to store instantiation information in a global variable but use a
> static variable within the class itself (at least that's what I remember
> from the GOF book).
Have this seen in implementations (XOOPS).
> But with you method, how would I access the object so it could be
> created automatically?
makeInstance determines if the class is a singleton, if yes, it checks
the global array if we have an object yet. Otherwise we get a new
object. If you prefer you can store the objects in a static var of
makeInstance instead of a global.
>>> // Must be done this way, because call_user_func does not
>>> // return references:
>>> $tmpObj = call_user_func (array ($realClassName, 'getInstance));
Drats!
This works but is ugly:
class singleton {
function &getInstance(&$ref) {
static $obj = null;
if (!is_object($obj)) { $obj = new singleton(); }
// pass back in arg. for call_user_func
$ref->instance =& $obj;
return $obj;
}
}
function &makeInstance($className) {
$realClassName = t3lib_div::makeInstanceClassName($className);
if (is_callable(array($realClassName, 'getInstance')) {
call_user_func(array($realClassName, 'getInstance'),&$tmpObj);
return $tmpObj->instance;
} else {
new $realClassName;
}
}
Now it's fashioned after the book. But I see really no advantage to a
global.
Masi
More information about the TYPO3-dev
mailing list