简体   繁体   English

symfony2在构造函数中重定向

[英]symfony2 redirect in constructor

I want to do a redirect in the constructor in a specific sutiation. 我想在构造函数中执行特定重定向。 I tried to do it like this: 我试图这样做:

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

and like this: 像这样:

return $this->redirect($url);

But it doesn't work. 但这是行不通的。 In every other method it works, but for some reason when this code is in the constructor it doesn't work. 它在所有其他方法中都有效,但是由于某种原因,当此代码在构造函数中时,它不起作用。 There are no errors or warnings. 没有错误或警告。

If you need more info ask in the comments. 如果您需要更多信息,请在评论中提问。 Thanks for the time. 感谢您的时间。

Bad idea to use redirect in constructors. 在构造函数中使用重定向的好主意。 Constructor return only current object of the class (object of controller in your case), and it can't return redirect object . 构造函数仅返回object of the class当前object of the class (在您的情况下为控制器的对象),而不能返回redirect object Maybe you can solve your task in route, using FrameworkBundle:Redirect:urlRedirect : 也许您可以使用FrameworkBundle:Redirect:urlRedirect解决路线中的任务:

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

Check examples in How to Configure a Redirect without a Custom Controller 查看如何在没有自定义控制器的情况下配置重定向的示例

Bad idea to redirect from controller directly. 直接从控制器重定向的坏主意。 I would rather throw some custom exception. 我宁愿抛出一些自定义异常。

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

Then, in Symfony , setup the ExceptionListener which will evaluate class-type of Exception thrown and redirect you application to another URL, if necessary. 然后,在Symfony ,设置ExceptionListener ,它将评估抛出的Exception类类型,并在必要时将您的应用程序重定向到另一个URL。 This service will most likely depend on @routing service to generate alternate URL destination. 此服务很可能将依赖@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);
        }
    }
}

This way to can maintain single error handling and redirection logic. 这样可以维护单个错误处理和重定向逻辑。 Too complicated? 太复杂?

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

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