2012-10-01 26 views
1

我的觀點是在某些軟件包中的所有控制器中調用通用函數(比如說AdminBundle)。我設置了一個包含true或false的會話的登錄監聽器,我需要在AdminBundle的每個方法之前檢查該會話。聽衆打包電話

於是,我就做一個__construct()函數在我AdminBundle控制器,但現在看來,我不能從這個方法對服務的訪問(因爲容器還沒有加載,所以我不能訪問此$ )。

最好的做法應該是在這些控制器的非常方法之前使用偵聽器調用此服務,但我無法弄清楚我需要使用的偵聽器(無法在Google上找到線索......)。

希望在不夠清楚,請不要猶豫,問問題,如果你不明白我的意思!

預先感謝任何解決方案/想法(如果你認爲我沒有使用正確的方式做到這一點,請解釋一下我自己的觀點!)

+1

也許這有助於:http://symfony.com/doc/2.0/book/internals.html#events或更簡潔:http://api.symfony.com/2.0/Symfony/Component/HttpKernel/KernelEvents。 html您可能正在尋找CONTROLLER事件 – dbrumann

+0

感謝我查看onKernelController偵聽器,但是我可以從此偵聽器獲得的唯一一件事是調用的操作,而不是捆綁軟件名稱。至於我試圖獲取這些信息的請求偵聽器。我真的不覺得有一種方法可以正確地做到這一點......如果我找不到方法,我會進行路線測試,但我不喜歡它。不管怎麼說,還是要謝謝你! – Snroki

回答

1

下午就這個問題後,我終於搞定感謝mahok的解決方案。

對於那些whitch這裏有同樣的問題,是我的控制器聽衆:

<?php 
namespace Site\MyBundle\Listener; 

use Symfony\Component\Security\Core\SecurityContext; 
use Symfony\Component\HttpKernel\HttpKernelInterface; 
use Symfony\Component\HttpKernel\Event\FilterControllerEvent; 
use Symfony\Component\HttpKernel\HttpKernel; 
use Symfony\Component\Routing\Router; 
use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Component\DependencyInjection\ContainerInterface; 

class ControllerListener 
{ 
    protected $container; 
    protected $router; 


    public function __construct(ContainerInterface $container, Router $router) 
    { 
     $this->router = $router; 
     $this->container = $container; 
    } 

    public function onKernelController(FilterControllerEvent $event) 
    {  
     if (HttpKernel::MASTER_REQUEST == $event->getRequestType()) 
     { 
      $controller = $event->getController(); 
      $controller = $controller[0]; 

      $new = new \ReflectionObject($controller); 

      if($new->getNamespaceName() == 'Site\MyBundle\Controller') 
      { 
       $test = $this->container->get('myservice')->test(); 
       if(empty($test) || !$test) 
       { 
        $index = $this->router->generate('index'); 
        $event->setController(function() use($index) { 
         return new RedirectResponse($index); 
        }); 
       } 
      } 
     } 
    } 
} 

所以基本上它比你的電流控制器的動作的命名空間與另一個,如果真的我查了一些變量知道,如果用戶可以在這裏或沒有。

再次感謝mahok你給我指路!