如何在 Symfony 4 中获取查询字符串

How to get query string in Symfony 4

我正在尝试访问 Symfony 4 中的查询字符串参数

namespace App\Controller;

use Symfony\Component\HttpFoundation\RequestStack;

class Home extends Controller {

    private $request;

    public function __construct(RequestStack $request){

        $this->request = $request;
    }

    public function getQueryString(){

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

       print_r($req); // see all the request data

       // $req -> grab the query parameters
       // return query parameters
    }
}

我用的是RequestStack,在打印getCurrentRequest()的结果的时候能看到一堆请求数据(包括我需要的查询参数),但是大部分方法都是private 我无法访问它们。

如何在 Symfony 中获取请求 URL 组件(包括查询参数)?

对于GET查询:

$this->request->getCurrentRequest()->query->get('name_query');

对于POST查询:

$this->request->getCurrentRequest()->request->get('name_query');
// retrieves $_GET and $_POST variables respectively
$request->query->get('id');
$request->request->get('category', 'default category');

来源https://symfony.com/doc/4.3/introduction/http_fundamentals.html#symfony-request-object

这适用于 Symfony 6:

GET

$value = $request->query->get('name_query');

POST

$value = $request->request->get('name_query');

BODY(REST API returns JSON 内部响应 body)

$value = $request->getContent();

HEADER

$value = $request->headers->get('X-header-name');