I don’t like singletons, but I have to compromise now (but only as temporary measure).
However I don’t want to go completely singleton. I’d rather want to use this pattern:
interface NameThisInterface {
//Returns the currently centralized object.
static function current();
//Centralizes the instance.
function centralize();
}
class A implements NameThisInterface {
...
}
$obj = new A;
$obj->centralize();
...
A::current(); //gets $obj.
Basically A would be my “Application” class. All controllers, models and views etc will access need only one instance of it. But for the sake of easier unit-testing among other reasons I want to have the application object stored as a reference to all MVC classes. So with the pattern above, the conversion at this later point in time will be easier and some of the unit testing might be easier.
Is there a generally accepted name for this pattern?
6
It is a combination of Singelton and some form of “Creator Patter” (probably a Factory (Though your factory is a little on the disorganized side (since we can’t see most of the code)).
There is nothing wrong with combining Singelton with other patterns. In fact I personally think that you can NOT use a singelton correctly unless you combine it with some other creator pattern (personal opinion). The reason is that tightly coupling your code to a single version of an object makes the code very inflexible and brittle (and hard to test).
Personally I like to formalize the factory and allow different versions to be registered (ie a test version/production version/an ISS version). Thus different factories can be used (one instantiated on start-up) depending on the situation thus the singelton is still created on demand (which is an important property of a singelton (especially if is a heavy weight object)).
3
Simon’s comment hit the nail on the head. What you’ve got there is almost exactly a global variable with get/set methods.
I say almost since your set method isn’t static; this will prevent you setting your global variable to null
after it has been assigned a value. You could debate whether this is a good thing. I’d argue “no”: remember there’s nothing forcing you to assign it a value in the first place!
If you have to dignify it with a name, maybe go with “global instance holder/container/etc”. If you make sure the word “global” is in there as much as possible (i.e. even on your getter/setter methods) it should stick out like a sore thumb to anyone using it.
1