我想在特定的情况下在构造函数中进行重定向。
我尝试这样做:
return new \Symfony\Component\HttpFoundation\RedirectResponse($url);
像这样:
return $this->redirect($url);
但这不起作用。在所有其他方法中它都有效,但由于某种原因,当此代码位于构造函数中时它不起作用。没有错误或警告。
如果您需要更多信息,请在评论中询问。
谢谢你的时间。
直接从控制器重定向是个坏主意。我宁愿抛出一些自定义异常。
class FooController{
public function __construct(){
if ( some_test ){
throw RedirectionException(); // name it however you like
}
}
}
然后,在Symfony
,设置ExceptionListener
这将评估类类型Exception
如有必要,抛出并将您的应用程序重定向到另一个 URL。这项服务很可能取决于@routing
生成备用 URL 目标的服务。
Service config:
services:
kernel.listener.your_listener_name:
class: Your\Namespace\AcmeExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
Listener class:
class AcmeExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
if ( $exception instanceof RedirectionException ){
$response = new RedirectResponse();
$event->setResponse($response);
}
}
}
这种方式可以维护单个错误处理和重定向逻辑。太复杂?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)