S
S
startproger2021-08-24 12:48:55
symfony
startproger, 2021-08-24 12:48:55

How to properly get a Request in a Symfony service?

You need to get the Request object in the service.

This can be done, as I understand it, in two ways:

  1. Call in the Symfony\Component\HttpFoundation\ RequestStack constructor and then call the getCurrentRequest() method from it
  2. Call the static method Symfony\Component\HttpFoundation\ Request::createFromGlobals()


Since the result is the same, I don't understand the difference between the two approaches. Please explain how they differ.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2021-08-24
@startproger

The second option is not working, you will not receive the current Request, but create a new one.
From the RequestStack you will get exactly the current Request, which contains attributes that can be added during application execution ( the current route, its parameters, etc)
But remember that the application is not necessarily executed in the web context, and the Request may not exist, so in ideally, to receive it in the controller, pull out the necessary parameters from there, which are already transferred to the service

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question