CakePHP中获取Request请求数据的几种方式

Request Parameters

Cake\Http\ServerRequest::getParam($name)
获取请求路由中的参数信息,如控制器名称、方法名称、方法参数等。

//URL:www.abc.com/users/edit/3

$this->request->getParam('controller'); //users
$this->request->getParam('action'); //edit
$this->request->getParam('pass'); //3

//$this->request->getParam('paging'); //获取分页相关信息,返回数组

Query String Parameters

Cake\Http\ServerRequest::getQueryParams()
Cake\Http\ServerRequest::getQuery($name)
获取请求路径中的查询部分,即“?”之后的部分。

//URL:www.abc.com/users/index?page=2&sort=id&direction=DESC

$this->request->getQuery('page'); //2
$this->request->getQueryParams(); //返回数组,包含所有查询参数

Request Body Data

Cake\Http\ServerRequest::getData( name, default = null)
获取POST请求传递的参数,不指定参数名称则获取全部参数,无匹配数据则返回null。

PUT, PATCH or DELETE Data

Cake\Http\ServerRequest::input( callback[, options])
获取PUT、PATCH、DELETE类型请求的数据,并可以使用回调函数形式的参数对数据进行处理,通常用于REST请求中JSON或XML格式的数据。

$jsonData = $this->request->input('json_decode');

Environment Variables (from SERVERand _ENV)

Cake\Http\ServerRequest::env( key, value = null)
该方法是对 env() 全局函数的封装,它同时具有 setter/getter 的能力,且不需要修改全局 $_SERVER$_ENV 变量。

//Get the host
$host = $this->request->env('HTTP_HOST');

//Set a value, generally helpful in testing.
$this->request->env('REQUEST_METHOD', 'POST');

//Get all the environment variables
$env = $this->request->getServerParams();

XML or JSON Data

//Get JSON encoded data submitted to a PUT/POST action
$jsonData = $this->request->input('json_decode');

//Get XML encoded data submitted to a PUT/POST action
$xmlData = $this->request->input('Cake\Utility\Xml::build', ['return' => 'domdocument']);

Path Information

Cake\Http\ServerRequest::getAttribute()
获取请求URL的路径信息,参数通常为 basewebroot

//URL: /subdir/articles/edit/1?page=1

//Holds /subdir/articles/edit/1?page=1
$here = $request->here();

//Holds /subdir
$base = $request->getAttribute('base');

Cookies

//Get the cookie value, or null if the cookie is missing.
$this->request->getCookie('CAKEPHP');

//Read the value, or get the default of 0
$this->request->getCookie('CAKEPHP', 0);

//Get all cookies as an hash
$this->request->getCookieParams();

//Get a CookieCollection instance (starting with 3.5.0)
$this->request->getCookieCollection()

猜你喜欢

转载自blog.csdn.net/hwhsong/article/details/78329836