How to Retrieve the Request from the Service Container

How to Retrieve the Request from the Service Container

Whenever you need to access the current request in a service, you can either add it as an argument to the methods that need the request or inject the request_stack service and access the Request by calling the [getCurrentRequest()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/HttpFoundation/RequestStack.php "Symfony\Component\HttpFoundation\RequestStack::getCurrentRequest()") method:

  1. // src/Newsletter/NewsletterManager.php
  2. namespace App\Newsletter;
  3. use Symfony\Component\HttpFoundation\RequestStack;
  4. class NewsletterManager
  5. {
  6. protected $requestStack;
  7. public function __construct(RequestStack $requestStack)
  8. {
  9. $this->requestStack = $requestStack;
  10. }
  11. public function anyMethod()
  12. {
  13. $request = $this->requestStack->getCurrentRequest();
  14. // ... do something with the request
  15. }
  16. // ...
  17. }

Now, inject the request_stack, which behaves like any normal service. If you’re using the default services.yaml configuration, this will happen automatically via autowiring.

Tip

In a controller you can get the Request object by having it passed in as an argument to your action method. See The Request object as a Controller Argument for details.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.