php 如何在 Symfony2 或 Symfony3 中检查请求是 POST 还是 GET 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22852305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:19:30  来源:igfitidea点击:

How can I check if request was a POST or GET request in Symfony2 or Symfony3

phpsymfonyrequesthttp-posthttp-get

提问by Gottlieb Notschnabel

I just wondered if there is a very easy way (best: a simple $this->container->isGet()I can call) to determine whether the request is a $_POSTor a $_GETrequest.

我只是想知道是否有一种非常简单的方法(最好:$this->container->isGet()我可以调用的简单方法)来确定请求是请求$_POST还是$_GET请求。

According to the docs,

根据文档,

A Request object holds information about the client request. This information can be accessed via several public properties:

  • request: equivalent of $_POST;
  • query: equivalent of $_GET($request->query->get('name'));

Request 对象保存有关客户端请求的信息。可以通过几个公共属性访问此信息:

  • request: 相当于$_POST;
  • query: 相当于$_GET( $request->query->get('name'));

But I won't be able to use if($request->request)or if($request->query)to check, because both are existing attributes in the Request class.

但我将无法使用if($request->request)if($request->query)检查,因为两者都是 Request 类中的现有属性。

So I was wondering of Symfony offers something like the

所以我想知道 Symfony 提供了类似的东西

$this->container->isGet();
// or isQuery() or isPost() or isRequest();

mentioned above?

上文提到的?

回答by Nighon

If you want to do it in controller,

如果你想在控制器中做到这一点,

$this->getRequest()->isMethod('GET');

or in your model (service), inject or pass the Request object to your model first, then do the same like the above.

或者在您的模型(服务)中,首先将 Request 对象注入或传递给您的模型,然后执行与上述相同的操作。

Edit: for Symfony 3 use this code

编辑:对于 Symfony 3 使用此代码

if ($request->isMethod('post')) {
    // your code
}

回答by timhc22

Or this:

或这个:

public function myAction(Request $request)
{
    if ($request->isMethod('POST')) {

    }
}

回答by Matheno

Since the answer suggested to use getRequest()which is now deprecated, You can do it by this:

由于建议使用的答案getRequest()现已弃用,您可以这样做:

$this->get('request')->getMethod() == 'POST'

回答by Azoel

Or this:

或这个:

use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();

    if ($request->getMethod() === 'POST' ) {
}

回答by HelpNeeder

You could do:

你可以这样做:

if($this->request->getRealMethod() == 'post') {
    // is post
}

if($this->request->getRealMethod() == 'get') {
    // is get
}

Just read a bit about requestobject on Symfony APIpage.

只需在Symfony API页面上阅读一些关于请求对象的内容。