symfony2 redirect in constructor

前端 未结 2 1832
心在旅途
心在旅途 2021-01-24 13:07

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         


        
相关标签:
2条回答
  • 2021-01-24 14:01

    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. Maybe you can solve your task in route, using 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

    0 讨论(0)
  • 2021-01-24 14:11

    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. This service will most likely depend on @routing service to generate alternate URL destination.

    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?

    0 讨论(0)
提交回复
热议问题