So I've done a new install of Symfony 3, trying to setup a few API routes, but I am unable to access the container inside my controllers.
My controller extends from the base Symfony controller, which has the ContainerAwareTrait
, but when I try doing $this->container->get('service')
I am getting this error:
"message": "Call to a member function get() on null",
"class": "Component\\Debug\\Exception\\FatalThrowableError",
"trace": [{
"namespace": "",
"short_class": "",
"class": "",
"type": "",
"function": "",
"file": "src\\Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller.php",
"line": 50,
"args": []
}]
Looks like symfony's own controller is unable to find the container, is there something I'm missing ?
Here is the controller's code:
use FOS\RestBundle\Controller\Annotations\Get;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
class UsersController extends Controller
{
/**
* @Get()
*
* @return JsonResponse
*/
public function getUsersAction()
{
$users= $this->get('doctrine.orm.entity_manager')->getRepository('AppBundle:User')->findAll();
return new JsonResponse($users, 200):
}
}
Finally found the answer thanks too @Cerad's comment: Symfony 3's default install creates the services.yml file, and registers every Controllers as a service. Disabling this allowed my controllers to access the container.
These are the guilty lines:
Try to setContainer method on the controllers :
add calls in your controller at service.yml
In controller you could access container with just using method
get()
on$this
, example: