RequestStack什么时候应该使用getMasterRequest而不是getCurrentRequest?

Since 2.4, we can inject the RequestStack in our services.

To retrieve the current Request, there is two methods:

/** @var Request */
$request = $requestStack->getCurrentRequest();

// OR

/** @var Request */
$request = $requestStack->getMasterRequest();

When should we use the currentRequest ?
And when should we use the masterRequest?

For example, if I need to retrieve the parameters in the body of the current Request, I would use:

$params = $request->request->all();

Which of the two methods should I use ?

When dealing with multiple requests, the non master request comes from internal requests. Usually from twig in the form of

{{ render(controller('foo')) }}

When the second request is created, only the request format and locale are copied to the new instance. Therefore, any data you would expect to come from the user, will not be available. This includes request parameters, ip address, and any HTTP headers.

In most situation, you will only need to deal with the current request. But, to answer your question, any time you need data coming from the user, you will require the master request. An example would be using the users IP address to pre-select a CountryType form control.

When using getMasterRequest()->getClientIp() you would be given the IP address of the user (something like 209.58.130.174). When calling it on the non master you will be given the localhost/loopback IP (127.0.0.1). There aren't really any methods that will return null, they simply return different information about how the request was created.

The master request is the one that comes from the original user; the subrequest is the one that you do internally — either with the forward() method of HttpKernel — or by the forward() helper of the framework's Controller class — or {% render ... %} in Twig.

https://stackoverflow.com/a/12456998/1078488

This means you would normally use the current request, if you don't explicitely want the actual request made by the user.

I've used a service for injecting the current request:

app.request:
    class: Symfony\Component\HttpFoundation\RequestStack
    factory:
        - '@request_stack'
        - 'getCurrentRequest'

Then you can inject it like this:

app.some_service:
    class: AppBundle\Service\SomeService
    arguments:
        - '@app.request'
        - '@some_other_service'