12

These seem to return the same thing:

\Drupal::request()

$request_stack->getCurrentRequest()

Which is the preferred way to get the current request and why? Is one of these to be deprecated? Any other advantages/disadvantages?

Thanks!

2
  • 3
    What context are you calling it in? Generally speaking if your context supports dependency injection, you would inject the request stack service and use it the latter way (better for testability). If you're in procedural code, e.g. a hook, you would use the former
    – Clive
    Oct 10 '18 at 22:15
  • Thanks, @Clive ... it is in a service that I didn't originally write and I had seen the other way from more time in hooks, but that makes sense. Thanks for the clarification! Oct 11 '18 at 14:19
18

How to get the current request object:

Procedural

In procedural code get the request from the static wrapper \Drupal:

$request = \Drupal::request();

Service

In a service get the request from the injected request stack:

$request = $this->requestStack->getCurrentRequest();

Controller

In a controller you can pull the request from the route argument stack by including a typed request parameter. An example from UserController:

use Symfony\Component\HttpFoundation\Request;

  public function resetPass(Request $request, $uid, $timestamp, $hash) {          
    // use $request
  }

It's not necessary to define the route parameter in the route definition. The request is always available.

Form

In a form method get the request from getRequest():

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $request = $this->getRequest();
    ...
  }

Don't use the injected requestStack property directly, because it is not available for all Form API callbacks.

5
  • Thanks! ... it is in a service that I didn't originally write and I had seen the other way from more time spent in hooks, but that makes sense. Thanks for the clarification! Oct 11 '18 at 14:20
  • How does a service get the injected request stack?
    – joachim
    May 8 '19 at 15:06
  • 4
    @joachim, the service needs @request_stack as argument. You find examples in core.services.yml.
    – 4k4
    May 8 '19 at 16:33
  • @4k4 Could you give us an example scenario of when the requestStack wouldn't be available if injected directly? Aug 26 '19 at 21:04
  • @HeitorAlthmann, if injected directly it would be available, but you can't be sure it is when using the form class in Form API. $request = $this->getRequest() gets the request from the injected service, but has a fallback in case it is not available.
    – 4k4
    Aug 27 '19 at 6:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.