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:

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

Then you need to create your event class:



 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();  


     if (!is_array($controller)) {  


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:

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: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s