1、Request請求對象
(1)擷取Request
擷取方式一:助手函數
$request = request();
擷取方式二:擷取執行個體(
單例模式))
use think\Request;
$request = Request::instance();
擷取方式三:注入到方法(推薦)
use think\Request;
public function requestInfo(Request $request)
{
$request;
}
(2)Request方法
請求路徑
GET http://127.0.0.1:8009/index/index/requestinfo/type/5.html?id=001
函數 | 說明 | 結果 |
domain() | 域名 | http://127.0.0.1:8009 |
pathinfo() | 路徑帶字尾 | index/index/requestinfo/type/5.html |
path() | 路徑不帶字尾 | index/index/requestinfo/type/5 |
method() | 請求類型 | GET |
isGet() | 是否為GET請求 | true |
isPost() | 是否為POST請求 | false |
isAjax() | 是否為ajax請求 | |
get() | 查詢參數 | Array([“id”] => “001”) |
get(“id”) | “001” | |
param() | 所有參數包括post | Array([“id”] => “001” [“type”] => “5”) |
param(‘type’) | 單個參數 | “5” |
post() | POST參數 | Array() |
session(‘name’, ‘jack’) | 設定session | - |
session() | 擷取session | Array([“name”] => “jack”) |
cookie(‘key’, ‘value’) | 設定cookie | |
cookie() | 擷取cookie | Array([“PHPSESSID”] => “734672fc1386d54105273362df904750” [“key”] => “value”) |
module() | 子產品 | index |
controller() | 控制器 | Index |
action() | 操作 | requestinfo |
url() | url帶查詢字元串 | /index/index/requestinfo/type/5.html?id=001 |
baseUrl() | 不帶查詢字元串 | /index/index/requestinfo/type/5.html |
(3)助手函數input
input('get.id')
// 相當于
$request->get('id')
// $request->參數類型(key名,key值,函數名);
$request->get('key','value','intval');
2、響應對象Response
方式一:通過配置檔案修改響應格式(整個子產品生效 )
conf/api/config.php
return [
'default_return_type'=>'json'
];
方式二:動态修改傳回類型
<?php
namespace app\api\controller;
use think\Config;
class Index
{
public function getUserInfo($type='json')
{
if(!in_array($type, ['json', 'jsonp', 'xml']))
{
$type = 'json';
}
Config::set('default_return_type', $type);
$data = [
'code' => 200,
'list' => [
'name'=> 'Tom',
'age'=>23
]
];
return $data;
}
}
通路:
http://127.0.0.1:8009/api/index/getuserinfo?type=json傳回
{
code: 200,
list: {
name: "Tom",
age: 23
}
}