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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s