How to Retrieve the Request from the Service Container

Version: 2.7
Edit this page

Warning: You are browsing the documentation for Symfony 2.7, which is no longer maintained.

Read the updated version of this page for Symfony 5.3 (the current stable version).

How to Retrieve the Request from the Service Container

As of Symfony 2.4, instead of injecting the request service, you should 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 AppBundle\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:

  • YAML
  • XML
  • PHP
1
2
3
4
5
# src/AppBundle/Resources/config/services.yml
services:
    newsletter_manager:
        class:     AppBundle\Newsletter\NewsletterManager
        arguments: ["@request_stack"]

Almost all Symfony2 built-in services behave in the same way: a single instance is created by the container which it returns whenever you get it or when it is injected into another service. There is one exception in a standard Symfony2 application: the request service.

If you try to inject the request into a service, you will probably receive a ScopeWideningInjectionException exception. That's because the request can change during the life-time of a container (when a sub-request is created for instance).

Tip

If you define a controller as a service then you can get the Request object without injecting the container by having it passed in as an argument of your action method. See Controller for details.

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