Symfony2依赖性注射;不能与控制器一起工作


Symfony2 dependecy injection doesn't work with controller

根据Symfony2 Cookbook,我试图通过依赖注入来保护控制器,但我收到了错误Catchable Fatal Error: Argument 1 passed to Acme'ExampleBundle'Controller'DefaultController::__construct() must implement interface Symfony'Component'Security'Core'SecurityContextInterface, none given, called in /var/www/example/app/cache/dev/classes.php on line 4706 and defined in /var/www/example/src/Acme/ExampleBundle/Controller/DefaultController.php line 13

这是我的服务。yml

parameters:
    acme_example.default.class: Acme'ExampleBundle'Controller'DefaultController
services:
    acme_example.default:
        class: %acme_example.default.class%
        arguments: [@security.context]

和控制器:

namespace Acme'ExampleBundle'Controller;
use Symfony'Bundle'FrameworkBundle'Controller'Controller;
use Symfony'Component'HttpFoundation'Response;
use Symfony'Component'Security'Core'Exception'AccessDeniedException;
class DefaultController extends Controller {
    public function __construct(SecurityContextInterface $securityContext)
    {
        if(false === $securityContext->isGranted('IS_AUTHENTICATED_FULLY'))
        {
            throw new AccessDeniedException();
        }                
    }
    public function indexAction()
    {
        return new Response('OK');
    }
}

如果将控制器配置为服务,则在路由中引用它们时需要使用稍微不同的语法。应该使用acme_example.default:indexAction而不是AcmeExampleBundle:Default:index

确保控制器中的use Symfony'Component'Security'Core'SecurityContextInterface;。如果没有它,构造函数中的SecurityContextInterface类型提示将无法解析。

此外,请确保您的控制器实际上是作为服务调用的。你发布的错误是抱怨没有发送到构造函数,这听起来像是你在以"默认"方式使用控制器。请参阅本烹饪书页面,了解如何将控制器设置为服务。

类Symfony''Bundle''FrameworkBundle''Controller''Controller扩展了Containerware基类。这个类通过$container-local属性访问整个容器,所以不应该向控制器服务注入任何服务,因为可以通过$this->container->get('security.context')访问SecurityContext。