Hooking into request event - Symfony PHP

665 Views Asked by At

Normally when using services in Symfony PHP I would inject them into controllers like so:

use App\Services\Utilities;

class Home extends Controller {

    public function __construct(Utilities $u){

        $u->doSomething();
    }
}

But I would only have access to this service if the Home controller is called (/ route matched).

I'd like to invoke a method on every request in Symfony 4 - even requests that are redirected or return 404's - before the response is returned.

So..

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

What would be the best place in the application to inject this service?

1

There are 1 best solutions below

0
On BEST ANSWER

You can creates subscriber to request event, something like that:

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