Symfony2 controller as a service and the service_container

5.10.2011
NOTE from 1.5 years later: This is not best practice. If you want a testable controller or write a reusable bundle, you should take the effort to inject the services you actually need, instead of extending the symfony base controller. For rapid development however, i would still recommend this as the base controller methods are very convenient.

I often want to have my controllers be a service so you can inject some information. But at the same time i like to extend the base controller Symfony\Bundle\FrameworkBundle\Controller\Controller to have the convenience methods like $this->render. Now if you just create a service from your controller, you won't be able to use the methods anymore. You will get exceptions about calling get() on a non-object.
What you need to do is inject the service_container to your controller manually.

In XML, this looks like this:




<service id="liip_vie.viecontroller" class="%liip_vie.viecontroller.class%" public="true">
<argument type="service" id="service_container"/>
...
</service>


In YML, it looks like this




services:
liip_vie.viecontroller:
class: %liip_vie.viecontroller.class%
arguments:
- "@service_container"
- ...


And your constructor will look like this:




use Symfony\Component\DependencyInjection\ContainerInterface;
...
public function __construct(ContainerInterface $container, ...)
{
$this->setContainer($container);
...
}


Hope this helps. At least i always forget how to do it. Now i know where to look it up when i need it next time :-)

symfony