Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code before controller's action

Tags:

symfony

I would like execute code before all actions in my project (to calculate an important global variable). How to set a pre-action function in my controllers ?

like image 714
bux Avatar asked Jun 06 '12 11:06

bux


3 Answers

There's no pre-action method in Symfony2. You have to use event listeners for that purpose.

like image 169
Samy Dindane Avatar answered Nov 09 '22 02:11

Samy Dindane


Probably using listeners is more elegant way to implement "after controller initialized tasks", but there is more simplified way to do it:

use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Override method to call #containerInitialized method when container set.
 * {@inheritdoc}
 */
public function setContainer(ContainerInterface $container = null)
{
    parent::setContainer($container);
    $this->containerInitialized();
}

/**
 * Perform some operations after controller initialized and container set.
 */
private function containerInitialized()
{
     // some tasks to do...
}

Insert this code into your controller, or, if you prefer you can even insert it into some base parent abstraction of your controllers.

because container will be set to each controller when its initialized, we can override setContainer method to perform some tasks after container set.

like image 29
pleerock Avatar answered Nov 09 '22 00:11

pleerock


You should especially read this documentation page: http://symfony.com/doc/current/cookbook/event_dispatcher/before_after_filters.html

like image 11
Żabojad Avatar answered Nov 09 '22 01:11

Żabojad