Request类解析
request是请求相关的封装对象,比如原本我们想要获取get参数需要使用$_GET,post参数使用$_POST,字符串流数据通过file_get_contents(“php://input”)。而在实例化request对象时,这类参数都被组装到该对象。
类属性
名称 | 类型 | 真实含义 |
---|---|---|
$instance | object | Request对象实例 |
$method | string | 请求方式 |
$domain | string | 域名(含协议和端口) |
$url | string | URL地址 |
$baseUrl | string | 基础URL |
$baseFile | string | 当前执行的文件 |
$root | string | 访问的ROOT地址 |
$pathinfo | string | pathinfo |
$path | string | pathinfo(不含后缀) |
$routeInfo | array | 当前路由信息 |
$env | array | 环境变量 |
$dispatch | array | 路由调度信息 |
$module | string | 请求调用模块名 |
$controller | string | 请求调用控制器 |
$action | string | 请求调用操作器(控制器方法) |
$langset | string | 当前语言集 |
$param | array | 请求参数组合变量 |
$get | array | GET请求参数 |
$post | array | POST请求参数 |
$request | array | $_REQUEST |
$put | array | PUT请求参数 |
$session | array | SESSION变量 |
$file | array | 上传FILE参数 |
$cookie | array | Cookie信息 |
$server | array | $_SERVER信息 |
$header | array | HTTP请求头部信息 |
$mimeType | array | 资源类型\ |
$input | string | php://input数据 |
实例化
/**
* 构造函数
* @access protected
* @param array $options 参数
*/
protected function __construct($options = [])
{
//options要求格式为二维数组,使用property_exists()判断键名是否为request类的变量,若是则设置值
foreach ($options as $name => $item) {
if (property_exists($this, $name)) {
$this->$name = $item;
}
}
//设置filter函数列表
if (is_null($this->filter)) {
$this->filter = Config::get('default_filter');
}
// 保存 php://input
$this->input = file_get_contents('php://input');
}
/**
* 初始化
* @access public
* @param array $options 参数
* @return \think\Request
*/
public static function instance($options = [])
{
if (is_null(self::$instance)) {
self::$instance = new static($options);
}
return self::$instance;
}
这两段代码属于一个功能,共同服务于实例化Request对象。
- instance($options = [])以单例模式进行实例操作,防止Request对象被多次创造。
- __construct($options = []) 实现类实例化的逻辑
$option参数可传入Request类的属性,在初始化阶段即可进行赋值。
然后再设置过滤器和存储input流数据
通过以上内容,实现了Request的创建,每次通过instance()静态方法调用获取。
Hook自定义方法
public function index()
{
$request = Request::instance();
//闭包