2013-04-09 35 views
4

我正在嘗試編寫需要訪問用戶權限級別的事件偵聽器。在控制器我用下面的代碼Symfony 2:獲取控制器外部的安全上下文

代碼:

$securityContext = $this->container->get('security.context'); 

if($securityContext->isGranted('ROLE_USER')){ 
    //Do Something 
} 

但是控制器我不能工作,如何獲得安全上下文之外。可能嗎?

+0

這可能幫助:http://stackoverflow.com/questions/7561013/injecting-securitycontext-services-into-a-listener-class-in-symfony2-causes-circ – 2013-04-09 16:50:21

回答

20

要做到這一點,最好的辦法是通過使用Service Container(如phpisuber說)依賴注入。但是,而不是注入整個容器(這被認爲是不好的做法,因爲它使整個班級少可測試並打破鬆耦合),你應該注入security.context服務,像這樣:

acme_foo.bar_service: 
    class: %acme_foo.bar_service.class% 
    arguments: 
     - @security.context 

您的服務可以是這樣的:

<?php 
namespace Acme\FooBundle\Service; 

use Symfony\Component\Security\Core\SecurityContext; 

class BarService 
{ 
    /** 
    * @var SecurityContext 
    */ 
    protected $context; 

    /** 
    * @param SecurityContext $context 
    */ 
    public function __construct($context) 
    { 
     $this->context = $context; 
    } 

    public function doSomething() 
    { 
     return $this->context->isGranted('ROLE_USER'); 
    } 
} 
5

有兩種方式來獲得它的控制器之外:

依賴注入:

這是做了正確的方式,你需要的是文檔here英寸

mybundle.model.mymodel: 
class: %mybundle.model.myclass% 
arguments: [@servicecontainer] 

快速和骯髒的:

global $kernel; 
$securityContext = $kernel->getContainer()->get('security.context'); 
+2

請不要使用快速和骯髒的解決方案!你永遠不應該使用全球! – 2013-04-10 09:44:13

+0

這個解決方案徹底打破了[Demeter法](http://en.wikipedia.org/wiki/Law_of_Demeter) – Touki 2013-04-10 09:54:09

+2

@Touki關心更多解釋?我真的很感興趣。 RamonKleiss是正確的,Q&D解決方案不是一個好主意,但是我將它包含在那些想通過symfony配置將20分鐘的facedesking注入模型之前進行快速概念檢查的人員。測試你的代碼,然後返回並正確注入容器。 Mmmhm。 – phpisuber01 2013-04-10 12:14:44

相關問題