繁体   English   中英

symfony2在构造函数中重定向

[英]symfony2 redirect in constructor

我想在构造函数中执行特定重定向。 我试图这样做:

return new \Symfony\Component\HttpFoundation\RedirectResponse($url);

像这样:

return $this->redirect($url);

但这是行不通的。 它在所有其他方法中都有效,但是由于某种原因,当此代码在构造函数中时,它不起作用。 没有错误或警告。

如果您需要更多信息,请在评论中提问。 感谢您的时间。

在构造函数中使用重定向的好主意。 构造函数仅返回object of the class当前object of the class (在您的情况下为控制器的对象),而不能返回redirect object 也许您可以使用FrameworkBundle:Redirect:urlRedirect解决路线中的任务:

# redirecting the root
root:
    path: /
    defaults:
        _controller: FrameworkBundle:Redirect:urlRedirect
        path: /app
        permanent: true

查看如何在没有自定义控制器的情况下配置重定向的示例

直接从控制器重定向的坏主意。 我宁愿抛出一些自定义异常。

class FooController{
    public function __construct(){
        if ( some_test ){
            throw RedirectionException(); // name it however you like
        }
    }
}

然后,在Symfony ,设置ExceptionListener ,它将评估抛出的Exception类类型,并在必要时将您的应用程序重定向到另一个URL。 此服务很可能将依赖@routing服务生成备用URL目标。

服务配置:

services:
    kernel.listener.your_listener_name:
        class: Your\Namespace\AcmeExceptionListener
        tags:
            - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

侦听器类:

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

这样可以维护单个错误处理和重定向逻辑。 太复杂?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM