【问题标题】:Redirect response from Event Subscriber in Symfony PHPSymfony PHP 中事件订阅者的重定向响应
【发布时间】:2018-11-11 00:24:03
【问题描述】:

我正在尝试从与 Synfony PHP 中的内核事件挂钩的事件订阅者返回永久 (301) 重定向响应。

我的订阅者如下:

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

use Symfony\Component\HttpFoundation\RedirectResponse;

class KernelSubscriber implements EventSubscriberInterface {

    public function __construct() {

        // some stuff here but not relevant for this example
    }

    public static function getSubscribedEvents(): array {

        return [ KernelEvents::REQUEST => 'onRequest' ];
    }

    public function onRequest(GetResponseEvent $event): void {

        // if conditions met
        //     301 redirect to some internal or external URL

        if(!$event->isMasterRequest()) return;
    }   
}

如果这是一个控制器,我会返回 $this->redirectToRoute('route') 或类似的东西,但从 onRequest 方法返回是在一个完全不同的上下文中。

如何从该事件订阅者返回响应(特别是重定向)?

【问题讨论】:

    标签: php symfony symfony4 php-7.2


    【解决方案1】:

    应该是这样的:

    $event->setResponse(new RedirectResponse($route));
    

    【讨论】:

    • 它告诉我:No route found for "GET http://localhost:8000/home" (from "http://localhost:8000/login")。我怎样才能得到$route ??
    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2020-11-21
    • 2021-01-29
    • 2013-11-24
    相关资源
    最近更新 更多