一、簡(jiǎn)介
在ThinkPHP5中,所有的請(qǐng)求都被封閉到請(qǐng)求對(duì)象think\Request類中,在很多場(chǎng)合下并不需要實(shí)例化調(diào)用,通常使用依賴注入即可。在其它場(chǎng)合(例如模板輸出等)則可以使用think\facade\Request靜態(tài)類操作。
總結(jié)如下,獲取ThinkPHP5中請(qǐng)求獲取一個(gè)請(qǐng)求資源可以通過(guò)以下三種方法:
1)依賴注入(由think\Request類負(fù)責(zé))
2)使用 think\facade\Request 靜態(tài)類
3)助手函數(shù)(request())
ThinkPHP關(guān)于請(qǐng)求的核心方法都定義于核心文件thinkphp\library\think\Request.php中。
二、獲取請(qǐng)求對(duì)象
1、依賴注入
1)構(gòu)造方法注入
/**
* 構(gòu)造方法
* @param Request $request Request對(duì)象
* @access public
* 需要:use think\Request;
*/
public function __construct(Request $request)
{
$this->request = $request;
}
2)繼承控制器基類think\Controller
如果你繼承了系統(tǒng)的控制器基類think\Controller的話,系統(tǒng)已經(jīng)自動(dòng)完成了請(qǐng)求對(duì)象的構(gòu)造方法注入了,你可以直接使用$this->request屬性調(diào)用當(dāng)前的請(qǐng)求對(duì)象。
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function index() {
return $this->request->param();
}
}
3)也可以在每個(gè)方法中使用依賴注入
public function index(Request $request) {
return $request->param('name');
}
2、其它
通過(guò)助手函數(shù) 和 Facade調(diào)用 的方式這里不做詳細(xì)介紹,詳情可以查看官方文檔。
三、Request常用方法
1、URL
| 方法 | 含義 | 例子 |
|---|---|---|
| host | 當(dāng)前訪問(wèn)域名或者IP | nosee123.com |
| scheme | 當(dāng)前訪問(wèn)協(xié)議 | http |
| port | 當(dāng)前訪問(wèn)的端口 | 80 |
| domain | 當(dāng)前包含協(xié)議的域名 | http://nosee123.com |
| url | 獲取完整URL地址 不帶域名 | /Index/welcome |
| url(true) | 獲取完整URL地址 包含域名 | http://nosee123.com/Index/welcome |
2、路由
| 方法 | 含義 |
|---|---|
| module | 獲取當(dāng)前模塊 |
| controller | 獲取當(dāng)前控制器 |
| action | 獲取當(dāng)前操作方法 |
3、請(qǐng)求頭
$data = $request->header();
echo '<pre>';
var_dump($data);
//獲取結(jié)果:
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、請(qǐng)求數(shù)據(jù)
| 方法 | 含義 | 例子 |
|---|---|---|
| method | 當(dāng)前請(qǐng)求類型(大寫(xiě)) | GET |
| isGet、isPost、isPut、isDelete等 | 判斷是否是某種請(qǐng)求 | |
| isMobile | 判斷是否手機(jī)訪問(wèn) | false |
| isAjax | 判斷是否AJAX請(qǐng)求 | false |
| param | 獲取當(dāng)前的請(qǐng)求數(shù)據(jù),包括post、get等 | |
| post | 獲取post請(qǐng)求數(shù)據(jù) | |
| get | 獲取get請(qǐng)求數(shù)據(jù) |
四、參數(shù)綁定
參數(shù)綁定是把當(dāng)前請(qǐng)求的變量作為操作方法(也包括架構(gòu)方法)的參數(shù)直接傳入,參數(shù)綁定并不區(qū)分請(qǐng)求類型。
詳情可以查看官方文檔:https://www.kancloud.cn/manual/thinkphp5_1/353991