Symfony Controller unable to access container

此生再无相见时 提交于 2019-12-11 05:00:02

问题


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

回答1:


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:

   AppBundle\Controller\:       
        resource: '../../src/AppBundle/Controller'      
        public: true        
        tags: ['controller.service_arguments']



回答2:


Try to setContainer method on the controllers :

add calls in your controller at service.yml

 AppBundle\Controller\:
        resource: '../../src/YourBundle/YourController'
        public: true
        tags: ['controller.service_arguments']
        calls:
            - [setContainer, ["@service_container"]]



回答3:


In controller you could access container with just using method get() on $this, example:

$this->get('security.token_storage')


来源:https://stackoverflow.com/questions/44446763/symfony-controller-unable-to-access-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!