Padraic Brady is back today with the second part of his "Dependency Injection in Zend Framework 2.0" series. In this second post he talks about what dependency injection containers are (and aren't) and how they could lead to bad practices if they're considered as service locators.
For Part 2, we’re going to dig more into what a DIC is and isn’t. I’ve already noted one very simple DIC called Pimple which will continue as one of my reference points since it best illustrates just how simple a DIC can be. In Part 3, we’ll (finally) turn our attention to some actual source code. Baby steps. Parts 1 and 2 should get you thinking so that ZF 2.0′s DIC is a lot easier to understand and critique. We don’t want anyone panicking just by throwing them into the deep end.
He talks more about the Pimple DIC tool and how, despite it's similarity to a set of Factory pattern calls, it's slightly different - think of it as "a container of executable Factories". He introduces the concept of a Service Locator, an object that can find and load other objects in an intelligent way. He notes that the most ideal DIC is an "external agent" that defines the object relationships outside of the application.
He points out a feature of ZF2 that allows for injection of the DIC into a controller, allowing it to look up the resources it needs. This of course, has issues - three that he mentions specifically:
- Firstly, this isn’t Dependency Injection.
- Secondly, it creates objects which are useless without the specific DIC interface it depends on.
- Thirdly, DICs are really bad Service Locators.