Re: When to instantiate a new class
| From: | Larry Garfield | Date: | Sun, 28 Jun 2015 16:39:18 +0000 |
| Subject: | Re: When to instantiate a new class | ||
| References: | 1 2 3 4 5 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-324975@lists.php.net to get a copy of this message | ||
On 06/28/2015 03:12 AM, Jesse Schalken wrote:
On Sun, Jun 28, 2015 at 4:05 AM, Larry Garfield <larry@garfieldtech.com> wrote:*snip* I understood what you meant. I'm saying that's still a Service Locator. Just because it's not one single global god object doesn't mean you're not using it as a service locator. In your example, your class is now coupled to its real dependencies, but only implicitly. Implicit dependencies are a great source of bugs and accidental tight coupling. It's also coupled to your dependency wrapper object. So you've added more dependencies this way, one of them a hard dependency. Now try to unit test your Foo class. You need to mock the BarService *and* your extra wrapper. You've added extra steps and complication that offer no additional value over wiring an object directly to its dependencies, and you've made the code less explicit and less maintainable. A DIC doesn't have to be a huge complex affair like in Java. :-) Look into Pimple. It's the simplest DIC you'll find, and is readily understandable. It gets you all of the benefits of DI with a very simple configuration approach (just write code) that gives you all the benefits of your interstitial, with no downsides. --Larry GarfieldWhat you describe is a service locator. Which is basically the same thing as a dependency injection container that you pass into the object you're using. Google "service locator bad" for why you shouldn't do that. :-)"Service Locator" (according to this <http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/> and this <https://en.wikipedia.org/wiki/Service_locator_pattern>) seems to be when you have a global registry mapping class names (or some other key) to some means of instantiating that class/service. That *would* cause problems. What I was describing was something simple like this: