Posts

Showing posts from February 21, 2013

Controllers as Services in Symfony2

Controller as a service is continually touted as the best practice. But why would I wrap a controller into a service? That's good question. Well, the point of doing this in general is not having to inject the DI container into your controllers (instead, you inject the dependencies into the controller directly). Thus the controller no longer depends on the container. Good: You get added flexibility. You no longer hard-code which services to use into your controller. You can specify that in the DI configuration instead. Example: You inject a UserProvider into the UserController for /profile, but inject a FacebookUserProvider into the same UserController for /profile/facebook. Bad: You must manually configure your dependencies in the DIC config. You need to manually assign the injected dependencies. Optional dependencies are no longer lazy-loaded. This is basically just a proof of concept to show how it could be done. namespace Acme\DemoBundle\Controller; class FooContr