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 ?
There's no pre-action method in Symfony2. You have to use event listeners for that purpose.
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.
You should especially read this documentation page: http://symfony.com/doc/current/cookbook/event_dispatcher/before_after_filters.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With