1

Symfony2 有没有办法在每个页面加载时调用控制器函数?目前我的解决方案是使用 ajax 调用,但我想在后端部分解决这一切。(当然不必复制每个控制器功能上的功能名称)

4

1 回答 1

1

您可以使用它创建Event Listener和处理KernelEvents::CONTROLLER事件(在过滤器之前),如此处所述

示例
Acme\DemoBundle\EventListener\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\Resources\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 }
于 2013-07-02T07:14:07.823 回答