gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:40:55 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com