所以我重新安装了 Symfony 3,尝试设置一些 API 路由,但我无法访问 Controller 内的容器。
我的 Controller 从基本 Symfony Controller 扩展而来,该 Controller 具有 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 自己的 Controller 无法找到容器,是我缺少什么吗?
这是 Controller 的代码:
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):
}
}
最佳答案
终于找到答案了,谢谢@Cerad的评论: Symfony 3 的默认安装会创建 services.yml 文件,并将每个 Controller 注册为服务。禁用此功能允许我的 Controller 访问容器。
这些是有罪的行:
AppBundle\Controller\:
resource: '../../src/AppBundle/Controller'
public: true
tags: ['controller.service_arguments']
关于php - Symfony Controller 无法访问容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44446763/