一、属性
1. $_rawBody 原生body内容
2. $_bodyParams body内参数
// 原生body内容
private $_rawBody;
//body参数
private $_bodyParams;
二、方法
1.getRawBody方法,返回原生请求体
//返回原生请求内容
public function getRawBody()
{
if ($this->_rawBody === null) {
$this->_rawBody = file_get_contents('php://input');
}
return $this->_rawBody;
}
2. setRawBody方法,设置请求体内容
// 设置请求内容
public function setRawBody($rawBody)
{
$this->_rawBody = $rawBody;
}
3. getBodyParams方法,解析请求体内容
/**
* 返回请求体中给定的请求参数。
*/
public function getBodyParams()
{
if ($this->_bodyParams === null) {
//隐藏字段请求方法
if (isset($_POST[$this->methodParam])) {
$this->_bodyParams = $_POST;
//删除请求方法
unset($this->_bodyParams[$this->methodParam]);
return $this->_bodyParams;
}
// MIME type
$rawContentType = $this->getContentType();
if (($pos = strpos($rawContentType, ';')) !== false) {
// e.g. text/html; charset=UTF-8
$contentType = substr($rawContentType, 0, $pos);
} else {
$contentType = $rawContentType;
}
//获取对应解析器
if (isset($this->parsers[$contentType])) {
$parser = Yii::createObject($this->parsers[$contentType]);
//解析器类应该实现RequestParserInterface接口
if (!($parser instanceof RequestParserInterface)) {
throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the yii\\web\\RequestParserInterface.");
}
//解析数据
$this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
} elseif (isset($this->parsers['*'])) {
//设置了默认解析器
$parser = Yii::createObject($this->parsers['*']);
if (!($parser instanceof RequestParserInterface)) {
throw new InvalidConfigException('The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.');
}
$this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
} elseif ($this->getMethod() === 'POST') {
// PHP has already parsed the body so we have all params in $_POST
$this->_bodyParams = $_POST;
} else {
$this->_bodyParams = [];
//解析GET/POST/COOKIE数据并设置全局变量
mb_parse_str($this->getRawBody(), $this->_bodyParams);
}
}
return $this->_bodyParams;
}
4. setBodyParams方法,设置请求体参数
//设置参数
public function setBodyParams($values)
{
$this->_bodyParams = $values;
}
5. getBodyParam方法,返回指定值内容
//返回指定的请求体参数值
public function getBodyParam($name, $defaultValue = null)
{
$params = $this->getBodyParams();
if (is_object($params)) {
// unable to use `ArrayHelper::getValue()` due to different dots in key logic and lack of exception handling
try {
return $params->{$name};
} catch (\Exception $e) {
return $defaultValue;
}
}
return isset($params[$name]) ? $params[$name] : $defaultValue;
}
6. post方法,返回指定的参数值
// 返回指定的参数值
public function post($name = null, $defaultValue = null)
{
if ($name === null) {
return $this->getBodyParams();
}
return $this->getBodyParam($name, $defaultValue);
}
总结:
阅读了2个属性和6个方法:
-
$_rawBody 原生body内容
-
$_bodyParams body内参数
- getRawBody方法,返回原生请求体
- setRawBody方法,设置请求体内容
- getBodyParams方法,解析请求体内容
- setBodyParams方法,设置请求体参数
- getBodyParam方法,返回指定值内容
- post方法,返回指定的参数值