连接到请求事件 - Symfony PHP
Hooking into request event - Symfony PHP
通常在 Symfony 中使用服务时 PHP 我会像这样将它们注入控制器:
use App\Services\Utilities;
class Home extends Controller {
public function __construct(Utilities $u){
$u->doSomething();
}
}
但只有调用 Home 控制器(/ 路由匹配),我才能访问此服务。
我想在 Symfony 4 中对 每个 请求调用一个方法 - 即使是重定向的请求或 return 404 - 在响应为 return编辑。
所以..
Request --> $u->doSomething() --> Response
在应用程序中注入此服务的最佳位置是什么?
您可以创建订阅者来请求事件,类似这样:
<?php declare(strict_types=1);
namespace App\EventSubscribers;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestSubscriber implements EventSubscriberInterface
{
private $utilites;
public function __construct(Utilites $something)
{
$this->utilites = $something;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => 'onRequest'
];
}
public function onRequest(GetResponseEvent $event): void
{
if (!$event->isMasterRequest()) {
return;
}
$this->utilites->doSoemthing();
}
}
通常在 Symfony 中使用服务时 PHP 我会像这样将它们注入控制器:
use App\Services\Utilities;
class Home extends Controller {
public function __construct(Utilities $u){
$u->doSomething();
}
}
但只有调用 Home 控制器(/ 路由匹配),我才能访问此服务。
我想在 Symfony 4 中对 每个 请求调用一个方法 - 即使是重定向的请求或 return 404 - 在响应为 return编辑。
所以..
Request --> $u->doSomething() --> Response
在应用程序中注入此服务的最佳位置是什么?
您可以创建订阅者来请求事件,类似这样:
<?php declare(strict_types=1);
namespace App\EventSubscribers;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestSubscriber implements EventSubscriberInterface
{
private $utilites;
public function __construct(Utilites $something)
{
$this->utilites = $something;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => 'onRequest'
];
}
public function onRequest(GetResponseEvent $event): void
{
if (!$event->isMasterRequest()) {
return;
}
$this->utilites->doSoemthing();
}
}