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() 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();
        // ... сделать что-то с запросом
    }

    // ...
}

Теперь, просто внедрите request_stack, который ведёт себя, как любой нормальный сервис. Если вы используете конфигурацию services.yml по умолчанию , это случится автоматически благодаря автомонтажу.

Tip

В контроллере вы можете получить объект Request, передав его в качестве аргумента к вашему методу действия. Смотрите , чтобы узнать детали.