tp6 + api
- 创建api的基类
1.1 标准api有三部分组成: code(状态码),msg(消息),data(数据)
1.2 在资源控制器中(此时是在User.php)
public function index()
{
return Response::create([1,2,3],'json');
}
这里可以点进去看看create底下的源码
- 封装基类
在app\controlle下新建一个Base.php
//抽象类
abstract class Base
{
protected function create($data,$msg = '',$code = 200,$type = 'json')
{
//标准api的生成
$result = [
'code' => ,
'msg' => ,
'data' => $data
];
//返回api接口
return Response::create($result,$type);
}
}
- 返回资源控制器,继承基类
class User extends Base
public function index()
{
// 获取数据列表
$data = UserModel::field('id,username,gender')->select();
//判断是否有值
// return $this ->create($data,$data->isEmpty()?'数据不存在' : '数据请求成功');
return $this -> create($data,'数据请求成功',201);
}
- 生成api接口
//在终端运行
php think run -H tp6.api.com