2012-01-17 47 views
1

根据Symfony2 Cookbook我试图通过dependecy注入到安全控制器,但我发现了错误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 13Symfony2的dependecy注入不带控制器的工作

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

回答

2

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

0

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

此外,请确保您的控制器实际上被称为服务。你发布的错误是抱怨没有任何被发送到构造函数,这听起来像你使用控制器'默认'的方式。有关如何将控制器设置为服务的信息,请参见this cookbook page

0

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