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() |
域名 |
|
pathinfo() |
路径带后缀 |
index/index/requestinfo/type/5.html |
path() |
路径不带后缀 |
index/index/requestinfo/type/5 |
method() |
请求类型 |
GET |
isGet() |
是否为GET请求 |
true |
isPost() |
是否为POST请求 |
false |
isAjax() |
是否为ajax请求 |
false |
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 } }