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

Con*_*tch 66 php request symfony

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

$this->getRequest()->get('value1');
$this->getRequest()->get('value2');
Run Code Online (Sandbox Code Playgroud)

有没有办法将这些合并到一个会返回数组的语句中?像Zend的getParams()之类的东西?

Gui*_*dre 145

你可以做到$this->getRequest()->query->all();获得所有GET参数并$this->getRequest()->request->all();获得所有POST参数.

所以在你的情况下:

$params = $this->getRequest()->request->all();
$params['value1'];
$params['value2'];
Run Code Online (Sandbox Code Playgroud)

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

  • 要获取路径中参数的值(例如/ posts/{id}),请使用`$ request-> attributes-> all()`.我正在使用`$ request-> get()`认为这是获取这些数据的唯一方法,并来到这里寻找另一种方式. (7认同)

Aft*_*eed 9

使用最新的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());
        }

    }
Run Code Online (Sandbox Code Playgroud)