Symfony2是否有办法在每个页面加载时调用控制器函数?在我的解决方案中,我的解决方案是使用ajax调用,但我想在后端部分解决这个问题。 (当然不必在每个控制器功能上复制功能名称)
答案 0 :(得分:1)
您可以使用Event Listener
创建KernelEvents::CONTROLLER
并处理described here事件(过滤前)。
示例强>:
的Acme \ DemoBundle \事件监听\ DemoListener.php
namespace Acme\DemoBundle\EventListener;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class DemoListener
{
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
/*
* $controller passed can be either a class or a Closure.
* This is not usual in Symfony2 but it may happen.
* If it is a class, it comes in array format
*/
if (!is_array($controller)) {
return;
}
$controller[0]->fooBarMethod();
}
}
的Acme \ DemoBundle \资源\ services.yml
parameters:
acme_demo.event_listener.class: Acme\DemoBundle\EventListener\DemoListener
services:
acme_demo.event_listener:
class: %acme_demo.event_listener.class%
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }