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.
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:
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 theget()
shortcut: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.