【问题标题】:Hooking into request event - Symfony PHP挂钩请求事件 - Symfony PHP
【发布时间】:2018-11-09 01:33:43
【问题描述】:

通常在 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

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

【问题讨论】:

标签: php symfony symfony4 php-7.2


【解决方案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();
    }
}

【讨论】:

    猜你喜欢
    • 2010-10-31
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 2016-09-22
    • 2013-04-01
    • 1970-01-01
    • 2017-11-27
    • 2019-04-02
    相关资源
    最近更新 更多