2012-01-17 48 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。