|
Posted by Rob Wilkerson on 11/15/07 22:36
On Nov 14, 6:33 pm, Michael Fesser <neti...@gmx.de> wrote:
> .oO(Rob Wilkerson)
>
> >I suppose I just don't understand the concept of "globally
> >available from everywhere in your scripts" if a "new" instance is
> >actually being created with each request.
>
> OK. I just meant that you can easily access the singleton from within
> every other function or method in your currently running script:
>
> function foo() {
> $obj = TMyClass::getInstance();
> $obj->doSomething();
>
> }
>
> Wherever you need the singleton, you just have to call the getInstance()
> method. It's like the 'global' keyword for importing global variables
> into the local scope, but IMHO cleaner and more flexible. Of course the
> next HTTP request is an entirely different thing and starts it all over
> again.
I guess what I keep coming back to is that this seems to have limited
practical use as a singleton. True, its instantiation becomes global
despite the fact that it may was instantiated (in your example) within
a traditionally scoped element (a function), but that seems like a
minor - and almost accidental - benefit. I don't tend to use
standalone functions that have no context, so scoping issues don't
really come up.
Additionally, my working practice is to use dependency injection
rather than create objects "on demand". That gives me a certain level
of controlled immutability. And, since the length of a request is so
short, it's usually pretty easy to feel reasonably secure that, during
the life of that request, an object instantiated in the "normal"
manner hasn't mutated to any kind of unusable (or unexpected) state
(perhaps I'm just naive?).
Anyway, I'm not trying to be difficult. Just trying to understand how
to best use singletons in a PHP context, their capabilities and their
limitations. You all have been a lot of help and I appreciate it.
Navigation:
[Reply to this message]
|