Reply to comment

Symfony2 controller as a service and the service_container

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 :-)

Trackback URL for this post:

http://davidbu.ch/mann/trackback/62

Reply

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.