Ada beberapa peringatan tentang secara langsung mengakses objek permintaan dengan cara ini di \Drupal::request
:
* Note: The use of this wrapper in particular is especially discouraged. Most
* code should not need to access the request directly. Doing so means it
* will only function when handling an HTTP request, and will require special
* modification or wrapping when run from a command line tool, from certain
* queue processors, or from automated tests.
*
* If code must access the request, it is considerably better to register
* an object with the Service Container and give it a setRequest() method
* that is configured to run when the service is created. That way, the
* correct request object can always be provided by the container and the
* service can still be unit tested.
Setiap pengontrol formulir yang diperpanjang \Drupal\Core\Form\FormBase
secara otomatis memiliki ketergantungan ini disuntikkan, dan dapat diakses menggunakan:
$this->getRequest()->getSchemeAndHttpHost()
Saya pikir (tetapi belum diuji) bahwa perpanjangan pengontrol halaman biasa \Drupal\Core\Controller\ControllerBase
dapat menyediakan request_stack
layanan dengan mengesampingkan \Drupal\Core\Controller\ControllerBase::create
fungsi, dan kemudian menetapkan $request
properti di konstruktor. Ini dijelaskan dengan sangat baik untuk formulir, dan proses yang sama harus berlaku untuk pengontrol halaman: https://www.drupal.org/docs/8/api/services-and-dependency-injection/dependency-injection-for-a- bentuk .