Adding a “preExecute” method to symfony2 controllers

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

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();
// not a controller do nothing
$controllerObject = $controller[0];
if(is_object($controllerObject) && method_exists($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>

3. In your controller

public function preExecute()
// your code goes here

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

More To Explore

How much does it cost to build a website in South Africa

How much does it cost to build a website in South Africa?

Clients often ask me “How much do you charge to build a website?”, and my standard response is: “How long is a piece of string”. See, the cost of website design & development in South Africa can vary from anything between R 1500 to R150 000 and even more.


Magento Experts in South Africa

If you have tried finding Magento Experts in South Africa I suspect you may have realized that it’s slim pickings out there with only 3 South African companies listed on the Magento Partners portal and a handful of developers