0

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

1 Answer 1

1

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.