Symfony,将所有请求重定向到侦听器内的特定路由

时间:2017-11-27 10:38:43

标签: symfony-2.8

我使用symfony 2.8并且我想将所有请求重定向到一个名为'即将到来'的路线,但它对我不起作用。还有更好的解决方案吗?

浏览器错误

  

ERR_TOO_MANY_REDIRECTS

这是听众:

    kernel.listener.redirect_listener:
    class: BaseBundle\Listener\RedirectListener
    arguments: [ '@router' ]
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

这是听众:     

namespace BaseBundle\Listener;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class RedirectListener
{
    public function __construct(Router $router)
    {
        $this->router = $router;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = new Request();

        $routeName = $request->get('_route');

        if (!$event->isMasterRequest() and $routeName == 'coming-soon') {
            return;
        }

        $response = new RedirectResponse($this->router->generate('coming-soon'));

        $event->setResponse($response);
    }
}

1 个答案:

答案 0 :(得分:0)

通过 $ event-> getRequest() - > get(' _route'); 获取路径名称而不是 $ request

public function onKernelRequest(GetResponseEvent $event)
{

    $routeName = $event->getRequest()->get('_route');

    if ($event->isMasterRequest() and $routeName == 'coming-soon') {
        return;
    }

    $response = new RedirectResponse($this->router->generate('coming-soon'));

    $event->setResponse($response);
}