嗨,我在symfony2中有一个事件监听器,我也相应地注册了,它需要在我的模块中任何控制器的任何函数调用之前调用。但是它调用了整个应用程序,我是说每个模块。但我希望它只在有人打开My Module时才被调用。
//My Event Listener
namespace Edu'AccountBundle'EventListener;
use Doctrine'ODM'MongoDB'DocumentManager;
use Symfony'Bundle'FrameworkBundle'Routing'Router;
use Symfony'Component'HttpFoundation'Session'Session;
use Symfony'Component'HttpKernel'Event'FilterControllerEvent;
use Edu'AccountBundle'CommonFunctions'CommonFunctions;
use Symfony'Component'HttpFoundation'RedirectResponse;
use Edu'AccountBundle'Controller'FinancialYearController;
/*
* Class:BeforeControllerListener
* @DESC:its a Listener which will execute at very first of any action of any controller in Account module (Act as a beforeFilter Symfony2)
* @param : @session,@route,@db
* @sunilrawat@indivar.com
* @09-07-2015
*/
class BeforeControllerListener
{
private $session;
private $router;
private $commonFunctions;
public function __construct(Session $session, Router $router, DocumentManager $dm)
{
$this->session = $session;
$this->router = $router;
$this->dm = $dm;
$this->commonFunctions = new CommonFunctions();
}
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
if (!is_array($controller)) {
return;
}
if (!$controller[0] instanceof FinancialYearController) {
if ($this->commonFunctions->checkFinancialYear($this->dm) !== 0 ) {
return;
}
$this->session->getFlashBag()->add('error', 'OOPS!, YOU MUST CREATE FINANCIAL YEAR TO MAKE ANY PROCESS IN ACCOUNTS!');
$redirectUrl= $this->router->generate('financialyear');
$event->setController(function() use ($redirectUrl) {
return new RedirectResponse($redirectUrl);
});
}
}
}
//Services.xml
<service id="edu.account.listener" class="Edu'AccountBundle'EventListener'BeforeControllerListener">
<argument type="service" id="session"/>
<argument type="service" id="router"/>
<argument type="service" id="doctrine_mongodb.odm.document_manager"/>
<tag name="kernel.event_listener" event="kernel.controller" method="onKernelController"/>
</service>
现在,当方法正确地调用任何控制器的任何动作的开始,但它是调用整个项目的每个控制器,而不是我希望它只在我的特定模块在我的应用程序中调用。
请指导这里缺少什么。提前感谢
对于每个控制器调用kernel.controller
事件侦听器是很正常的,重要的是事件侦听器内部的检查,如果控制器不匹配,它允许您提前返回。
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
if (!is_array($controller)) {
return;
}
if (!$controller[0] instanceof FinancialYearController) {
return;
}
if ($this->commonFunctions->checkFinancialYear($this->dm) !== 0 ) {
return;
}
$this->session->getFlashBag()->add('error', 'OOPS!, YOU MUST CREATE FINANCIAL YEAR TO MAKE ANY PROCESS IN ACCOUNTS!');
$redirectUrl= $this->router->generate('financialyear');
$event->setController(function() use ($redirectUrl) {
return new RedirectResponse($redirectUrl);
});
}
}