php - 在 Symfony PHP 中重定向来自事件订阅者的响应

标签 php symfony symfony4 php-7.2

我正在尝试从连接到 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;
    }   
}

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

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

最佳答案

应该是这样的:

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

关于php - 在 Symfony PHP 中重定向来自事件订阅者的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53244734/

相关文章:

php - 扩展 PHP 网站

php - '<?=' 在 PHP 中是什么意思?

php - 准备好的语句 LIKE 通配符

database - Symfony2 没有创建供应商表

php - 如果匿名用户无权访问 URL,如何将匿名用户重定向到自定义页面而不是登录页面?

symfony - 多文件验证 : "This value should be of type string"

php - 将 Symfony 3 应用程序连接到( Asterisk 服务器)中的外部 SQL 数据库

Symfony2 应用程序在 kernel.request 和 kernel.controller 之间总是有 3 秒的等待

security - Symfony $controller->getUser() 在非安全区域的替代方案?

javascript - 在 app.js Symfony 4 文件中加载 Assets