【发布时间】:2016-07-04 04:18:05
【问题描述】:
嗨,我在 symfony2 中有一个事件监听器,我也相应地注册了它,它需要在我的模块中任何控制器的任何函数调用之前调用。但它正在调用整个应用程序,我的意思是每个模块。但我希望只有在有人打开我的模块时才调用它。
//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>
现在,当方法在任何控制器的任何操作的开始时正确调用,但它正在调用整个项目的每个控制器时,我希望它只在我的应用程序的我的特定模块中调用。
请指导其中缺少的内容。 提前致谢
【问题讨论】:
-
您的代码检查您的控制器是否不是财政年度的实例,不应该相反吗?
if ( $controller[0] instanceof FinancialYearController) { -
我已经尝试过了,但没有工作,仍然需要为所有 mudules 调用每个控制器。
-
所以现在我正在考虑修复我的模块的路由,并在上面的函数中检查它们,我找不到更好的方法来做到这一点。