Trying to swap a controller using an event listener with Symfony2

前端 未结 1 1089
情话喂你
情话喂你 2020-12-30 07:56

I\'ve been reading through the internals chapter in the Symfony2 docs and it says if I add a listener to the kernel.controller event I can swap the controller that gets run,

相关标签:
1条回答
  • 2020-12-30 08:57

    You can set your controller to any callable, which means something like

    • A static method array('class', 'method')
    • An instance method array($instance, 'method')
    • An anonymous function function() { ... }
    • A regular global function 'function';
    • An instance of a class implementing the __invoke() method new MyClassImplementingInvoke()
    • The special syntax 'class::method' which forces the ControllerResolver to create a new instance of class (calling the constructor without any argument) and returning a callable array($instanceOfClass, 'method')

    EDIT:

    I looked up the wrong ControllerResolver. When running Symfony in a standard setup it'll use the Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver (and not the Symfony\Component\HttpKernel\Controller\ControllerResolver). So the controller name will be handled a little bit different to what I wrote above.

    The following example sums up all the possible options you have when setting your controller.

    public function onKernelController(FilterControllerEvent $event)    
    {
        $controller = $event->getController();
        // call method in Controller class in YourBundle
        $replacementController = 'YourBundle:Controller:method';
        // call method in service (which is a service registered in the DIC)
        $replacementController = 'service:method';
        // call method on an instance of Class (created by calling the constructor without any argument)
        $replacementController = 'Class::method';
        // call method on Class statically (static method)
        $replacementController = array('Class', 'method');
        // call method on $controller
        $controller            = new YourController(1, 2, 3);
        $replacementController = array($controller, 'method');
        // call __invoke on $controller
        $replacementController = new YourController(1, 2, 3);
        $event->setController($replacementController);
    }
    
    0 讨论(0)
提交回复
热议问题