How to create a something like Zend preDispatch method in Symfony2

前端 未结 2 1837
南笙
南笙 2020-12-28 19:04

I\'m making a project using a Symfony 2 and I need to have method like preDispatch in Zend which will be called before any action in the Controller. I\'m very new in Symfony

相关标签:
2条回答
  • 2020-12-28 19:21

    Symfony 1's preExecute() method made this very easy, but like you said, it's not available in Symfony2. Luckily, in Symfony2 you have access to events. The framework dispatches numerous events during your application's lifecycle. Here's a list of some of the events dispatched - http://symfony.com/doc/2.0/book/internals.html#events.

    You can also use the web debug toolbar to see what events are being dispatched, and the classes (EventListeners) that are listening to the event. That above link also goes into detail about the whole event system in case you're not familiar with it.

    Unfortunately I haven't had to mimic preExecute functionality myself, so I don't know exactly what event you would need to listen to, but I'm sure by reading the docs you'll figure out exactly what you need.

    Hope this helps.

    0 讨论(0)
  • 2020-12-28 19:24

    As @Arms suggested me, I've started exploring the event mechanism of Symfony 2. So now I'm gonna write down the code, that solved my problem (all configurations I'm doing in YAML, but you can do it in XML or PHP as well).

    At first you need to describe in Symfony configuration what kind of event would you like to listen and what the kernel should call when the event occurs. For this open the configuration file app\config\config.yml and add the following code:

    services:
        younamespace.yourbundle.listener.preexecute:
            class: Location\Of\Your\Listener\Class
            tags:
                - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
    

    Your class should implement the onKernelController method in the following way:

    public function onKernelController(FilterControllerEvent $event) {
        if(HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
            $controllers = $event->getController();
            if(is_array($controllers)) {
                $controller = $controllers[0];
    
                if(is_object($controller) && method_exists($controller, 'preExecute')) {
                    $controller->preExecute();
                }
            }
        }
    }
    

    After this every time when you create a preExecute method in your controller, it will be called before executing any actions, so you can do lot of stuff in that method, like initializing variables, or some checks before writing to DB and so on.

    You can also look at configuration in details here (this example is for kernel.request event, but it can help you to understand)

    Have fun ;)

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