Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have no access to container in my controller

I am trying to access a service in a Symfony Controller

$session = $this->get('session');

But I get the next error:

PHP Fatal error: Call to a member function get() on a non-object

I thought that Symfony2 had the controllers defined as services by default.

Note: this question was originally asked by Dbugger, but he removed it for no reason, while it was already answered.

like image 905
Emii Khaos Avatar asked Sep 25 '13 11:09

Emii Khaos


1 Answers

Using the container in controllers

get() is only a shortcut function provided by the Symfony base Controller class to access the container.

Your controller must extend this class to use this function:

namespace Acme\ExampleBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    // your actions
}

If you don't want to depend on this class (for some reasons) you can extend ContainerAware to get the container injected and use it like in the get() shortcut:

namespace Acme\ExampleBundle\Controller;
use Symfony\Component\DependencyInjection\ContainerAware;

class DefaultController extends ContainerAware
{
    public function exampleAction()
    {
        $myService = $this->container->get('my_service');

        // do something
    }
}

Creating controllers on your own

Controllers are not defined as services per default, you can define them, but it's not needed to get the container. If a request is made, the routing framework determines the controller, which need to be called. Then the controller gets constructed and the container is injected via the setContainer() method.

But if you construct the controller on your own (in a test or anywhere else), you have to inject the container on your own.

$controller = new DefaultController();
$controller->setContainer($container);
// $container comes trough DI or anything else.
like image 91
Emii Khaos Avatar answered Sep 20 '22 19:09

Emii Khaos