【问题标题】:How to get query string in Symfony 4如何在 Symfony 4 中获取查询字符串
【发布时间】:2019-02-18 20:25:46
【问题描述】:

我正在尝试访问 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 组件(包括查询参数)?

【问题讨论】:

    标签: php symfony request symfony4 php-7.2


    【解决方案1】:

    对于GET查询:

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

    对于POST查询:

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

    【讨论】:

      【解决方案2】:
      // 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

      【讨论】:

        【解决方案3】:

        这适用于 Symfony 6:

        获取

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

        发布

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

        BODY(REST API 在正文中返回 JSON 响应)

        $value = $request->getContent();
        

        标题

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-02-08
          • 2017-04-18
          相关资源
          最近更新 更多