Symfony 控制器无法访问容器

Symfony Controller unable to access container

所以我重新安装了 Symfony 3,尝试设置一些 API 路由,但我无法访问控制器中的容器。

我的控制器从基本的 Symfony 控制器扩展而来,它有 ContainerAwareTrait,但是当我尝试做 $this->container->get('service') 时,我收到这个错误:

"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": []
}]

看来 symfony 自己的控制器无法找到容器,是不是我遗漏了什么?

控制器代码如下:

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

在控制器中,您只需在 $this 上使用方法 get() 即可访问容器,示例:

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

终于找到答案了,也感谢@Cerad 的评论: Symfony 3 的默认安装会创建 services.yml 文件,并将每个控制器注册为服务。禁用它允许我的控制器访问容器。

这些是有罪的台词:

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

尝试在控制器上使用 setContainer 方法:

在控制器中添加调用 service.yml

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