ThinkPHP5.1学习笔记 - 请求

一、简介

在ThinkPHP5中,所有的请求都被封闭到请求对象think\Request类中,在很多场合下并不需要实例化调用,通常使用依赖注入即可。在其它场合(例如模板输出等)则可以使用think\facade\Request静态类操作。

总结如下,获取ThinkPHP5中请求获取一个请求资源可以通过以下三种方法:
1)依赖注入(由think\Request类负责)
2)使用 think\facade\Request 静态类
3)助手函数(request()

ThinkPHP关于请求的核心方法都定义于核心文件thinkphp\library\think\Request.php中。

二、获取请求对象

1、依赖注入

1)构造方法注入

/**
* 构造方法
* @param Request $request Request对象
* @access public
* 需要:use think\Request;
*/
public function __construct(Request $request)
{
    $this->request = $request;
}
    

2)继承控制器基类think\Controller
如果你继承了系统的控制器基类think\Controller的话,系统已经自动完成了请求对象的构造方法注入了,你可以直接使用$this->request属性调用当前的请求对象。

namespace app\index\controller;
use think\Controller;

class Index extends Controller
{
    public function index() {
        return $this->request->param();
    }    
}

3)也可以在每个方法中使用依赖注入

public function index(Request $request) {
    return $request->param('name');
}  

2、其它

通过助手函数 和 Facade调用 的方式这里不做详细介绍,详情可以查看官方文档。

三、Request常用方法

1、URL

方法 含义 例子
host 当前访问域名或者IP nosee123.com
scheme 当前访问协议 http
port 当前访问的端口 80
domain 当前包含协议的域名 http://nosee123.com
url 获取完整URL地址 不带域名 /Index/welcome
url(true) 获取完整URL地址 包含域名 http://nosee123.com/Index/welcome

2、路由

方法 含义
module 获取当前模块
controller 获取当前控制器
action 获取当前操作方法

3、请求头

$data = $request->header();
echo '<pre>';
var_dump($data);

//获取结果:
array(11) {
  ["cookie"]=>  string(36) "PHPSESSID=r6s2pe5eausr4l0o1j5tfi57eo"
  ["accept-language"]=>  string(14) "zh-CN,zh;q=0.8"
  ["accept-encoding"]=>  string(19) "gzip, deflate, sdch"
  ["referer"]=>  string(35) "http://nosee123.com/Index/index.html"
  ["accept"]=>  
  string(74) "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
  ["user-agent"]=>
  string(128) "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0"
  ["upgrade-insecure-requests"]=>  string(1) "1"
  ["connection"]=>  string(10) "keep-alive"
  ["host"]=>  string(11) "nosee123.com"
  ["content-length"]=>  string(0) ""
  ["content-type"]=>  string(0) ""
}

4、请求数据

方法 含义 例子
method 当前请求类型(大写) GET
isGet、isPost、isPut、isDelete等 判断是否是某种请求
isMobile 判断是否手机访问 false
isAjax 判断是否AJAX请求 false
param 获取当前的请求数据,包括post、get等
post 获取post请求数据
get 获取get请求数据

四、参数绑定

参数绑定是把当前请求的变量作为操作方法(也包括架构方法)的参数直接传入,参数绑定并不区分请求类型。

详情可以查看官方文档:https://www.kancloud.cn/manual/thinkphp5_1/353991

参考

官方手册:https://www.kancloud.cn/manual/thinkphp5_1/353985

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章