一、簡介
在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