Re: A modest proposal: __contructStatic
| From: | Patrick Schaaf | Date: | Sun, 15 Feb 2015 20:20:34 +0000 |
| Subject: | Re: A modest proposal: __contructStatic | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-82749@lists.php.net to get a copy of this message | ||
Am 15.02.2015 21:05 schrieb "Rowan Collins" <rowan.collins@gmail.com>:
>
> This sounds to me like you should just be using the Singleton pattern,
Of course this is singleton under the hood.
> // Now wherever in the code you want the default instance, just use this:
> $value = MyRedis::singleton()->get($key);
You can surely see how this is more readable / easier to write:
$value = MyRedir::get($key);
> The nice thing about an explicit Singleton is you can migrate to
Dependency Injection (call "$redis = MyRedis::singleton()" and start
passing the instance around,
I _can_ do that with my redis class, where I need it, by calling a method
MyRedis::link() which just returns $this. But the places where I need that
are rare.
> ... or to a cleverer factory / service locator (store more than one
instance in different static variables or a keyed array, to connect to
different stores for different purposes).
This i do with subclasses, where the subclass define suitable static
protected properties that guide the connect logic (which sits in the
baseclass). I have a global redis, a local redis (local to the host the
code runs on), a volatile redis (global, but does not make prersistent
dumps), and so on. Calling code ready red_global::this(),
red_volatile::that(), and so on. You don't get it better readable (and
greppable) as that.
> Making static calls implicitly access a singleton seems like it would
make code harder to read, and harder to extend,
I don't understand. It's the best to read to me. And the best to extend - I
just make another subclass.
Of course, there are places (in other classes) where stuff needs to use
such a redis instance without caring which one it is - i.e. an instances is
passed to a constructor there - in which case I can use the MyRedis::link()
method to get at the singleton instance.
But in most (I'd guess 90%) of the calling places, it's just the static
calls I need, and writing each of them as MyRedis::singleton()->xxx() is
more tedious.
best regards
Patrick