挂钩请求事件-Symfony PHP

时间:2018-11-09 01:33:44

标签: php symfony symfony4 php-7.2

通常在Symfony PHP中使用服务时,我会将它们注入到控制器中,如下所示:

use App\Services\Utilities;

class Home extends Controller {

    public function __construct(Utilities $u){

        $u->doSomething();
    }
}

但是,只有在调用Home控制器(/路由匹配)的情况下,我才能访问此服务。

我想在返回响应之前,对Symfony 4中的每个请求(甚至是重定向或返回404的请求)调用一个方法。

所以..

Request --> $u->doSomething() --> Response

在应用程序中注入此服务的最佳位置是什么?

1 个答案:

答案 0 :(得分:1)

您可以创建订阅者来请求事件,诸如此类:

<?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();
    }
}