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

2022-08-30 08:34:37

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

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

有没有办法将它们合并到一个返回数组的语句中?像Zend的getParams()这样的东西?


答案 1

您可以执行操作以获取所有 GET 参数并获取所有 POST 参数。$this->getRequest()->query->all();$this->getRequest()->request->all();

因此,在您的情况下:

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

有关 Request 类的详细信息,请参阅 http://api.symfony.com/2.8/Symfony/Component/HttpFoundation/Request.html


答案 2

使用最近的Symfony 2.6 +版本作为最佳实践,请求作为带有操作的参数传递,在这种情况下,您不需要显式调用$this->getRequest(),而是调用$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());
        }

    }

推荐