[英]How can I check if request was a POST or GET request in Symfony2 or Symfony3
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 $_POST
or a $_GET
request.我只是想知道是否有一种非常简单的方法(最好:一个简单的
$this->container->isGet()
我可以调用)来确定请求是$_POST
还是$_GET
请求。
According to the docs,根据文档,
A Request object holds information about the client request.
Request 对象包含有关客户端请求的信息。 This information can be accessed via several public properties:
可以通过几个公共属性访问此信息:
request
: equivalent of$_POST
;request
:相当于$_POST
;query
: equivalent of$_GET
($request->query->get('name')
);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?上文提到的?
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
}
Or this:或这个:
public function myAction(Request $request)
{
if ($request->isMethod('POST')) {
}
}
Or this:或这个:
use Symfony\Component\HttpFoundation\Request;
$request = Request::createFromGlobals();
if ($request->getMethod() === 'POST' ) {
}
由于答案建议使用现在已弃用的getRequest()
,因此您可以这样做:
$this->get('request')->getMethod() == 'POST'
You could do:你可以这样做:
if($this->request->getRealMethod() == 'post') {
// is post
}
if($this->request->getRealMethod() == 'get') {
// is get
}
Just read a bit about request object on Symfony API page.只需在Symfony API页面上阅读一些关于请求对象的信息。
In addition - if you prefer using constants:此外 - 如果您更喜欢使用常量:
if ($request->isMethod(Request::METHOD_POST)) {}
See the Request class:请参阅请求类:
namespace Symfony\Component\HttpFoundation;
class Request
{
public const METHOD_HEAD = 'HEAD';
public const METHOD_GET = 'GET';
public const METHOD_POST = 'POST';
public const METHOD_PUT = 'PUT';
public const METHOD_PATCH = 'PATCH';
public const METHOD_DELETE = 'DELETE';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.