我一直在阅读 Symfony2 文档中的内部章节,它说如果我向 kernel.controller 事件添加一个监听器,我可以交换运行的 Controller ,我有一些工作有点像这样:
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
$replacementControllerName = .... //Some logic to work out the name of the new controller
$replacementController = ?? //Not sure what goes here
$event->setController($replacementController);
}
我不确定是不是一旦我确定了替换 Controller 的名称,我如何获得可以传递给 setController 的实例?
最佳答案
您可以将 Controller 设置为任何 可调用 ,这意味着类似
array('class', 'method')
array($instance, 'method')
function() { ... }
'function'
; __invoke()
的类的实例方法 new MyClassImplementingInvoke()
'class::method'
这迫使 ControllerResolver
创建 class
的新实例(不带任何参数调用构造函数)并返回一个可调用的 array($instanceOfClass, 'method')
编辑:
我查错了
ControllerResolver
.在标准设置中运行 Symfony 时,它将使用 Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver
(而不是 Symfony\Component\HttpKernel\Controller\ControllerResolver
)。所以 Controller 名称的处理与我上面写的有点不同。以下示例总结了设置 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);
}
关于symfony - 尝试使用带有 Symfony2 的事件监听器交换 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6491505/