[Typo3-dev] singletons instead of pre-loaded objects
Martin T. Kutschker
Martin-no5pam-Kutschker at blackbox.n0spam.net
Mon Aug 9 20:47:06 CEST 2004
Robert Lemke wrote:
> Hi Martin,
>
> On Mon, 2004-08-09 at 18:16, Martin T. Kutschker wrote:
>
>>The idea is that in a global var we have an array that has references to
>>all classes that need only one instantiation, eg t3lib_db and t3lib_cs.
>
>
>>Instead of accessing them via a well known global var (eg t3lib_db) or
>>some pre-load mechanism (eg t3lib_cs) the code would simply call the
>>stattic method of tr3lib_div and will get a reference to the object. The
>>code in t3lib_div will either create a new object or pass the reference
>>of an existing one.
>
> okay, but I think that generally it is not a good idea to put
> instantiation information about singletons into some global array and
> access these functions like you suggested.
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).
> How about this: Every class which can be instantiated as a singleton
> (like t3lib_cs) must (or may) provide a method called "getInstance".
> Then t3lib_div::makeInstance could look like this (didn't check it, may
> be done differently):
>
> function &makeInstance($className) {
> $realClassName = t3lib_div::makeInstanceClassName($className);
> if (function_exists ($realClassName.'::getInstance')) {
> // Must be done this way, because call_user_func does not
> // return references:
> $tmpObj = $call_user_func (array ($realClassName, 'getInstance));
> return $tmpObj->getInstance();
> } else {
> new $realClassName;
> }
> }
>
> This would be 100% backwards-compatible and future code could take
> advantage of the singleton mechanism.
But this way you create every time a temp. object, so it's pointless.
The point is to avoid object creation.
Masi
More information about the TYPO3-dev
mailing list