Skip to main content

Adding a “preExecute” method to symfony2 controllers

As a  fan of the symfony framework, I have to admit that I have been a rather bad citizen when it comes to adopting symfony2. Stable releases of symfony2 have been around for some time now, yet up until recently I have opted for starting new projects on version 1.4.x for the simple reason that I was able to convince myself that there would not be enough time to “learn” symfony2.

However the more I read through the cookbook & documentation the more I realised that I would have to make time to learn symfony2, and boy has it been an experience. With the first long term support release (2.3) just around the corner I figured there is no time like the present and started digging really deep.

Being a long time user of symfony 1, I soon realized that some of the obvious features I have come to love have been omitted or has not yet been implemented in symfony2. One such feature is the “preExecute” method on controllers which allowed you to execute some logic in a controller prior to the actual execution of the requested action with out having to repeat the code inside of every action. this can be handy for things such as checking permissions etc. Fortunately the symfony2 framework makes implementing this feature a breeze once you understand how to add services to your application.

Here is how I implemented a “preExecute” method in my symfony2 application. I am sure there are better ways of doing this so any comments / feedback are welcome.

1. Create the listener:


namespace Project\SomeBundle\Listener;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class ControllerListener
{
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
if(!is_array($controller))
{
// not a controller do nothing
return;
}
$controllerObject = $controller[0];
if(is_object($controllerObject) && method_exists($controllerObject,"preExecute") )
{
$controllerObject->preExecute();
}
}
}

2. Register the listener as a service.
in services.xml

...
<service id="my.controller.listener">
<tag name="kernel.event_listener" event="kernel.controller" method="onKernelController"></tag>
</service>
...

3. In your controller


public function preExecute()
{
// your code goes here
}

The above method will now be executed before your “action” is called.

Wickass

Founder, Developer, Entrepreneur,PHP fan, Symfony Fan, Magento Fan, Mobile developer. Wannabe Blogger and general creator of stuff on the web

Leave a Reply

Your email address will not be published. Required fields are marked *