bux
bux

Reputation: 7739

Execute code before controller's action

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 ?

Upvotes: 30

Views: 34536

Answers (3)

pleerock
pleerock

Reputation: 18836

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.

Upvotes: 16

Żabojad
Żabojad

Reputation: 3095

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

Upvotes: 11

Samy Dindane
Samy Dindane

Reputation: 18706

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

Upvotes: 28

Related Questions