Execute code before controller's action

后端 未结 3 513
傲寒
傲寒 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.

提交回复
热议问题