Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages in full color showing how to combine Symfony with Docker, APIs, queues & async tasks, Webpack, Single-Page Applications, etc.

Buy printed version
WARNING: You are browsing the documentation for Symfony 2.8 which is not maintained anymore. Consider upgrading your projects to Symfony 5.1.

How to Retrieve the Request from the Service Container

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:

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
    1
    2
    3
    4
    5
    # src/AppBundle/Resources/config/services.yml
    services:
        newsletter_manager:
            class:     AppBundle\Newsletter\NewsletterManager
            arguments: ["@request_stack"]
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    <!-- src/AppBundle/Resources/config/services.xml -->
    <?xml version="1.0" encoding="UTF-8" ?>
    <container xmlns="http://symfony.com/schema/dic/services"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/services
            http://symfony.com/schema/dic/services/services-1.0.xsd">
    
        <services>
            <service
                id="newsletter_manager"
                class="AppBundle\Newsletter\NewsletterManager"
            >
                <argument type="service" id="request_stack"/>
            </service>
        </services>
    </container>
    
  • PHP
    1
    2
    3
    4
    5
    6
    7
    // src/AppBundle/Resources/config/services.php
    use AppBundle\Newsletter\NewsletterManager;
    use Symfony\Component\DependencyInjection\Reference;
    
    // ...
    $container->register('newsletter_manager', NewsletterManager::class)
        ->addArgument(new Reference('request_stack'));
    

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 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.