You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation.

How to Retrieve the Request from the Service Container

4.0 version

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() method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
namespace App\Newsletter;

use Symfony\Component\HttpFoundation\RequestStack;

class NewsletterManager
{
    protected $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function anyMethod()
    {
        $request = $this->requestStack->getCurrentRequest();
        // ... do something with the request
    }

    // ...
}

Now, just 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.