在 Symfony 2中获取所有请求参数

在 symfony 2控制器中,每次我想从 post 获取值时都需要运行:

$this->getRequest()->get('value1');
$this->getRequest()->get('value2');

有没有什么方法可以把它们合并到一个语句中,从而返回一个数组?

126315 次浏览

You can do $this->getRequest()->query->all(); to get all GET params and $this->getRequest()->request->all(); to get all POST params.

So in your case:

$params = $this->getRequest()->request->all();
$params['value1'];
$params['value2'];

For more info about the Request class, see http://api.symfony.com/2.8/Symfony/Component/HttpFoundation/Request.html

With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;


class SampleController extends Controller
{




public function indexAction(Request $request) {


var_dump($request->request->all());
}


}

Since you are in a controller, the action method is given a Request parameter.

You can access all POST data with $request->request->all();. This returns a key-value pair array.

When using GET requests you access data using $request->query->all();

For Symfony 3.4, you can access the data for both GET and POST, Like This

Post:

$data = $this->request->request->all();

Get:

$data = $this->request->query->all();

Well, remember this is always PHP, so you could just check for the superglobal variable $_REQUEST

https://www.php.net/manual/en/reserved.variables.request.php