Execute code before controller's action

后端 未结 3 493
傲寒
傲寒 2020-12-06 04:03

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 ?

相关标签:
3条回答
  • 2020-12-06 04:47

    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.

    0 讨论(0)
  • 2020-12-06 04:49

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

    0 讨论(0)
  • 2020-12-06 05:02

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

    0 讨论(0)
提交回复
热议问题