【问题标题】:Symfony2 dependecy injection doesn't work with controllerSymfony 依赖注入不适用于控制器
【发布时间】:2012-01-17 12:27:42
【问题描述】:

根据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

这是我的 services.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');
    }
}

【问题讨论】:

    标签: php dependency-injection symfony


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      另外,请确保您的控制器实际上是作为服务调用的。您发布的错误是抱怨 nothing 已发送到构造函数,这对我来说听起来像是您以“默认”方式使用控制器。请参阅this cookbook page,了解如何将控制器设置为服务。

      【讨论】:

        【解决方案3】:

        类 Symfony\Bundle\FrameworkBundle\Controller\Controller 扩展了 ContainerAware 基类。此类具有可通过 $container 本地属性访问的整个容器,因此您不应向控制器服务注入任何服务,因为您可以通过 $this->container->get('security.context') 访问 SecurityContext。

        【讨论】:

          猜你喜欢
          • 2012-04-23
          • 2014-11-15
          • 2023-03-26
          • 2016-02-01
          • 1970-01-01
          • 2012-12-31
          • 1970-01-01
          • 1970-01-01
          • 2017-06-16
          相关资源
          最近更新 更多