Symfony Controller unable to access container

2019-07-31 05:41发布

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

3条回答
SAY GOODBYE
2楼-- · 2019-07-31 05:56

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']
查看更多
贪生不怕死
3楼-- · 2019-07-31 05:58

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"]]

查看更多
Luminary・发光体
4楼-- · 2019-07-31 06:11

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

$this->get('security.token_storage')
查看更多
登录 后发表回答