且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试使用带有 Symfony2 的事件侦听器交换控制器

更新时间:2023-11-19 18:49:34

您可以将您的控制器设置为任何可调用,这意味着类似于

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

  • 一个静态方法array('class', 'method')
  • 一个实例方法array($instance, 'method')
  • 匿名函数 function() { ... }
  • 一个普通的全局函数'function';
  • 一个实现__invoke的类的实例() 方法 new MyClassImplementingInvoke()
  • 特殊语法 'class::method' 强制 ControllerResolver 创建一个 class 的新实例(不带任何参数调用构造函数)并返回一个可调用的 数组($instanceOfClass, '方法')
  • 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')

我查错了ControllerResolver.在标准设置中运行 Symfony 时,它将使用 Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver(而不是 Symfony\Component\HttpKernel\Controller\ControllerResolver).所以控制器名称的处理与我上面写的有点不同.

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);
}