一匣砖、簡介
在ThinkPHP5中,所有的請求都被封閉到請求對象think\Request類中煞烫,在很多場合下并不需要實(shí)例化調(diào)用浑此,通常使用依賴注入即可。在其它場合(例如模板輸出等)則可以使用think\facade\Request靜態(tài)類操作滞详。
總結(jié)如下凛俱,獲取ThinkPHP5中請求獲取一個(gè)請求資源可以通過以下三種方法:
1)依賴注入(由think\Request
類負(fù)責(zé))
2)使用 think\facade\Request
靜態(tài)類
3)助手函數(shù)(request()
)
ThinkPHP關(guān)于請求的核心方法都定義于核心文件thinkphp\library\think\Request.php
中紊馏。
二、獲取請求對象
1蒲犬、依賴注入
1)構(gòu)造方法注入
/**
* 構(gòu)造方法
* @param Request $request Request對象
* @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)完成了請求對象的構(gòu)造方法注入了,你可以直接使用$this->request屬性調(diào)用當(dāng)前的請求對象原叮。
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赫编、其它
通過助手函數(shù) 和 Facade調(diào)用 的方式這里不做詳細(xì)介紹,詳情可以查看官方文檔奋隶。
三擂送、Request常用方法
1、URL
方法 | 含義 | 例子 |
---|---|---|
host | 當(dāng)前訪問域名或者IP | nosee123.com |
scheme | 當(dāng)前訪問協(xié)議 | http |
port | 當(dāng)前訪問的端口 | 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嘹吨、請求頭
$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、請求數(shù)據(jù)
方法 | 含義 | 例子 |
---|---|---|
method | 當(dāng)前請求類型(大寫) | GET |
isGet境氢、isPost蟀拷、isPut、isDelete等 | 判斷是否是某種請求 | |
isMobile | 判斷是否手機(jī)訪問 | false |
isAjax | 判斷是否AJAX請求 | false |
param | 獲取當(dāng)前的請求數(shù)據(jù)萍聊,包括post问芬、get等 | |
post | 獲取post請求數(shù)據(jù) | |
get | 獲取get請求數(shù)據(jù) |
四、參數(shù)綁定
參數(shù)綁定是把當(dāng)前請求的變量作為操作方法(也包括架構(gòu)方法)的參數(shù)直接傳入脐区,參數(shù)綁定并不區(qū)分請求類型愈诚。
詳情可以查看官方文檔:https://www.kancloud.cn/manual/thinkphp5_1/353991