数据返回统一格式
app/common.php
对应目录创建文件
<?php
// 应用公共文件
// 统一返回格式
function show_res($code,$msg,$data,$httpCode=200){
$res = [
'code' => $code,
'msg' => $msg,
'data' => $data
];
return json($res,$httpCode);
}
config目录下部署
新建status.php
<?php
//返回值的代码符号
return[
//执行成功
'success' => 200,
//跳转
'goto' => 301,
//执行失败
'error' => 400,
//未登录
'not_login' => 401,
//没有权限
'not_auth' => 403,
//请求的资源不存在
'not_found' => 404,
//请求方式错误
'method_error' => 405,
//请求超时
'request_timeout' => 408,
//服务器内部错误
'server_error' => 500,
//服务不可用
'server_unavailable' => 503,
//网关超时
'gateway_timeout' => 504,
];
新建msg.php
<?php
//返回数据时对应的消息
return[
//执行成功
'success' => "请求成功",
//执行失败
'error' => "请求失败",
//未登录
'not_login' => "请合法登录",
//没有权限
'not_auth' => "未获得合法权限",
//请求的资源不存在
'not_found' => "请求的资源不存在",
//请求方式错误
'method_error' => "请求方式错误",
//请求超时
'request_timeout' => "请求超时",
//服务器内部错误
'server_error' => "服务器内部错误",
//服务不可用
'server_unavailable' => "服务不可用",
//网关超时
'gateway_timeout' => "网关超时",
//跳转
'goto' => "跳转",
];
新建redis.php
<?php
return [
//激活Token
"active_pre" => "active_account_pre_",
//登录Token
"token_pre" => "access_token_pre_",
//登录Token过期时间
"login_expire" => 24 * 3600,
//重置密码Token
"reset_pre" => "reset_password_pre_",
//登录验证码
"code_pre" => "login_pre_",
//登录验证码过期时间
"code_expire" => 120,
//登录验证码错误次数
"code_error" => 3,
//文件数据过期时间
"file_expire" => 3600 / 4,
];
搭建基础类库
app/common/business/lib
,自己依次添加目录,然后再创建下面的文件
Redis.php增删改查
<?php
namespace app\common\business\lib;
use think\facade\Cache;
class Redis
{
//公共成员变量,其实就是对应config/cache.php中的stores配置
private $store = null;
public function __construct($store = "redis")
{
$this->setStore($store);
}
/**
* @用途: Redis添加数据
*/
public function set($key, $value, $time = NULL)
{
return Cache::store($this->store)->set($key, $value, $time);
}
/**
* @用途: Redis获取数据
*/
public function get($key)
{
return Cache::store($this->store)->get($key);
}
/**
* @用途: Redis删除数据
*/
public function delete($key)
{
return Cache::store($this->store)->delete($key);
}
/**
* @用途: Redis修改数据
*/
public function update($key, $seconds, $value)
{
return Cache::store($this->store)->update($key, $seconds, $value);
}
public function setStore($store)
{
$this->store = $store;
return $this;
}
}
Token生成
<?php
namespace app\common\business\lib;
class Str
{
//生成token
public function createToken($str)
{
$tokenSalt = md5(uniqid(md5(microtime(true)), true));
return sha1($tokenSalt . $str);
}
//生成盐,用于密码加密
public function hiddenPassword($bit)
{
//盐字符集
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
$str = '';
for ($i = 0; $i < $bit; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
}
全局异常捕捉返回重构
app/common/exception/Http.php
对应目录下创建对应文件
<?php
namespace app\common\exception;
use think\exception\Handle;
use think\Response;
// 全局异常捕捉
class Http extends Handle
{
private $msg = NULL;
private $code = 0;
public function render($requset, \Throwable $e): Response
{
$this->msg = $e->getMessage();
$this->code = config('status.error');
// 如果传值为跳转
if ($this->msg == config('status.goto')) {
$this->code = config('status.goto');
}
return json([
'code' => $this->code,
'msg' => $this->msg,
'data' => NULL,
]);
}
}
新增基类控制器方法
以下代码在app/BaseController.php
文件内的abstract class BaseController
类中完成,相信聪明的你一定会知道这些代码应该放在哪些正确的位置!
use app\common\business\lib\Redis;
/**
* 自定义-Redis
*/
protected $redis = NULL;
/**
* 构造方法
* @access public
* @param App $app 应用对象
*/
public function __construct(App $app)
{
$this->app = $app;
$this->request = $this->app->request;
$this->redis = new Redis(); //添加这一行就可以,其他的不管
// 控制器初始化
$this->initialize();
}
//如果找不到方法,就会调用这个方法
public function __call($name, $arguments)
{
if (method_exists($this->app, $name)) {
return $this->fail("找不到{$name}方法");
}
}
public function show($code, $msg, $data)
{
return show_res($code, $msg, $data);
}
//成功时返回的数据
protected function success($res)
{
return $this->show(
//config助手函数,读取配置文件,意思是读取status.php中的success
config('status.success'),
config('msg.success'),
$res
);
}
//失败时返回的数据
protected function fail($res)
{
return $this->show(
//config助手函数,读取配置文件,意思是读取status.php中的success
config('status.error'),
config('msg.error'),
NULL
);
}
//获取token
protected function getToken()
{
$token = $this->request->header('access_token');
if (empty($token)) {
$token = $this->request->param('access_token');
}
return $token;
}
//获取用户状态
public function getUser()
{
// 获取配置中的token前缀拼接token值
return $this->redis->get(config('redis.token_pre') . $this->getToken());
}
//获取用户信息
public function getUid()
{
return $this->getUser()['id'];
}
搭建api接口
多应用模式下的操作!!!
app目录
|--api目录
|--config目录 //针对api应用下的独有配置
| |--cache.php //Redis缓存配置
| |--route.php //强制路由配置
|--middleware目录 //中间件拦截
| |--CheckingLogin.php //验证是否登录
|--controller目录
|--provider.php //声明引用重构全局异常捕捉文件
//cache.php
<?php
// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------
return [
// 默认缓存驱动
'default' => env('cache.driver', 'redis'),
// 缓存连接方式配置
'stores' => [
'redis' => [
// 驱动方式
'type' => 'redis',
'port' => 6379,
'host' => '127.0.0.1',
'select' => 10,
],
],
];
//route.php
<?php
// +----------------------------------------------------------------------
// | 路由设置
// +----------------------------------------------------------------------
return [
// pathinfo分隔符
'pathinfo_depr' => '/',
// URL伪静态后缀
'url_html_suffix' => 'html',
// URL普通方式参数 用于自动生成
'url_common_param' => true,
// 是否开启路由延迟解析
'url_lazy_route' => false,
// 是否强制使用路由
'url_route_must' => true, //基本上也就是修改这里
// 合并路由规则
'route_rule_merge' => false,
// 路由是否完全匹配
'route_complete_match' => false, //或者把这里也改成true
// 访问控制器层名称
'controller_layer' => 'controller',
// 空控制器名
'empty_controller' => 'Error',
// 是否使用控制器后缀
'controller_suffix' => false,
// 默认的路由变量规则
'default_route_pattern' => '[\w\.]+',
// 是否开启请求缓存 true自动缓存 支持设置请求缓存规则
'request_cache_key' => false,
// 请求缓存有效期
'request_cache_expire' => null,
// 全局请求缓存排除规则
'request_cache_except' => [],
// 默认控制器名
'default_controller' => 'Index',
// 默认操作名
'default_action' => 'index',
// 操作方法后缀
'action_suffix' => '',
// 默认JSONP格式返回的处理方法
'default_jsonp_handler' => 'jsonpReturn',
// 默认JSONP处理方法
'var_jsonp_handler' => 'callback',
];
//provider.php
<?php
use app\common\exception\Http;
// 容器Provider定义文件
return [
'think\exception\Handle' => Http::class,
];
//CheckingLogin.php
<?php
namespace app\api\middleware;
use app\BaseController;
class CheckingLogin extends BaseController
{
public function handle($request, \Closure $next)
{
$token = $this->getToken();
if (empty($token)) {
return $this->show(
config('status.not_login'),
config('msg.not_login'),
'非法请求!'
);
}
$user = $this->getUser();
if (empty($user)) {
return $this->show(
config('status.not_login'),
config('msg.not_login'),
'登录过期!'
);
}
//还可以添加其他的验证,比如权限验证,ip验证,异地登录,多设备登录等等
return $next($request);
}
}