2013-07-02 126 views
1

Symfony2有沒有在每次頁面加載時調用控制器功能的方法?在該解決方案中,我的解決方案是使用ajax調用,但我希望在後端部分解決這一切。 (當然,不必複製每個控制器功能上的功能名稱)在每次頁面加載時執行控制器的功能

回答

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 } 
相關問題