Dependency injection in ZF2 and Symfony 2 are service locators
Both ZF2 and Symfony 2 offer the same behavior: if I'm in a controller, and I want to use a service, I have to get it from the container with $this->get('my_service').
As such, the controller is not using DI, this is the service locator pattern. Controllers become more difficult to tests because of that, and they depend on the container now.
I wonder why both frameworks didn't go further: why not treat controllers like services and use dependency injection on them. In other words: if a controller needs a service "A", then it should get it in the constructor, or through setter/property injection.
That doesn't seem really complicated to me: instead of instantiating the controller, the MVC framework should just request it from the container (which would inject the dependencies like any other service).
So the questions: why was it done like that?
I develop a DI container and I don't want to use it as a service locator, but MVC frameworks don't seem built for this and integration seems difficult. (and I'm open to how other MVC frameworks work)
Posted Apr 13, 2013, 9:57 PM UTC · edited