Drupal and Web Request, most needed functionality
How to get the current request object
Procedural
In procedural code get the request from the static wrapper \Drupal:
$request = \Drupal::request();
The method Request(), returns a request object.
The Request object is a symfony technology and not Drupal's, so to understand its logic methods and internals, you can read more about it at: symfony.com/doc/current/components/http_foundation.html#request
so if you need the path created the request, use the following code:
$path = \Drupal::request()->getPathInfo();
Service
In a service get the current request from the injected argument @request_stack:
The module_name/module_name.services.yml file :
services:
custom.service:
class: Drupal\module_name\Service\CustomService
arguments:
- '@request_stack'
The module_name/src/Service/CustomService.php file :
use Symfony\Component\HttpFoundation\RequestStack;
/**
@var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
class customService {
public function __construct(RequestStack $requestStack) {
$this->requestStack = $requestStack;
}
public function doSomething() {
// use $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.