Symfony2 quick tips: How to create “filter” in the controller?

Do you remember in the Symfony 1.x preExecute and postExecute methods? 🙂 Yes? They were  cool but the Symfony2 has another (and a lot nicer) event manager . It name is Event Dispatcher. The Event Dispatcher is flexible and well-designed component and easy to use.

You should define your event in the app/config/config.yml:

 services:  
    test.controller_listener:  
     class: TestCompany\TestBundle\EventListener\TestListener  
     arguments: [ "HelloWorld" ]  
     tags:  
       - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }    

Then you need to create your event class:

/src/TestCompany/TestBundle/EventListener/TestListener.php

 <?php  

 namespace TestCompany\TestBundle\EventListener;  

 use Symfony\Component\HttpKernel\Event\FilterControllerEvent;  

 class TestListener {  

   private $test_argument_hello_world;  

   public function __construct($arguments) {  
     $this->test_argument_hello_world = $arguments;  
   }  

   public function onKernelController(FilterControllerEvent $event) {  
     $controller = $event->getController();  

     var_dump($this->test_argument_hello_world);  

     if (!is_array($controller)) {  
       return;  
     }  
   }  

 }  

It is very easy and for example you can also define arguments in the configuration. If you need more information you should read the documentation of Symfony2 Event Dispatcher: http://symfony.com/doc/current/components/event_dispatcher/introduction.html

This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a comment