¿Cómo puedo comprobar si la solicitud era una solicitud POST o GET en Symfony2 o Symfony3


Solo me preguntaba si hay una manera muy fácil (mejor: una simple $this->container->isGet() que pueda llamar) para determinar si la solicitud es una $_POST o una solicitud $_GET.

Según los documentos,

Un objeto Request contiene información sobre la solicitud del cliente. Este se puede acceder a la información a través de varias propiedades públicas:

  • request: equivalente a $_POST;
  • query: equivalente de $_GET ($request->query->get('name'));

Pero no podré usar if($request->request) o if($request->query) para comprobar, porque ambos son atributos existentes en la clase Request.

Así que me preguntaba de Symfony ofrece algo como el{[12]]}

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

Mencionado anteriormente?

Author: timhc22, 2014-04-04

5 answers

Si quieres hacerlo en el controlador,

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

O en su modelo (servicio), inyecte o pase el objeto de solicitud a su modelo primero, luego haga lo mismo como el anterior.

Editar: para Symfony 3 use este código

if ($request->isMethod('post')) {
    // your code
}
 53
Author: Nighon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-06 18:24:23

O esto:

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

    }
}
 36
Author: timhc22,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-14 16:05:53

Desde que la respuesta sugirió usar getRequest() que ahora está en desuso, Puedes hacerlo así:

$this->get('request')->getMethod() == 'POST'
 4
Author: Matheno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-28 11:30:34

O esto:

use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();

    if ($request->getMethod() === 'POST' ) {
}
 4
Author: Azoel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-13 09:45:44

Usted podría hacer:

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

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

Acaba de leer un poco acerca de solicitarobjeto en Symfony API página.

 0
Author: HelpNeeder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-21 01:57:58