接口继承类封装(超好用)

1.在controller文件夹下创建Apibase.php文件

 Apibase.php文件类容:

<?php
namespace app\controller;

use app\BaseController;
use app\model\User;
use think\App;
use think\exception\HttpResponseException;

// 需要操作报错返回code
define("OperationErr",504);
// 不需要操作返回code
define("Err",501);

class ApiBase extends BaseController {

    // 需要验证token的方法
    protected $in_action = [];

    protected $user;

    protected $root='';
    protected $controller='';
    protected $action='';

    //当前方法是否需要缓存
    private $now_action_is_cache = false;
    /*
     * 需要缓存的方法配置
     * 示例:$now_action_option['index'=>3600,...]
     */
    protected $now_action_option=[];

    /**
     * 构造函数
     * UserAdminBase constructor.
     */
    public function __construct (App $app) {
        parent::__construct($app);
        // 请求的控制器
        $this->controller = strtolower(Request()->controller());
        // 请求的方法
        $this->action = strtolower(Request()->action());

        $this->verification($this->controller,$this->action);
        $this->getPublicCache();
    }

    public function getUserId(){
        return $this->user?$this->user['id']:'';
    }

    /**
     * 验证需要登录的方法及token
     * @param $controller
     * @param $action
     * @return bool
     */
    public function verification($controller,$action)
    {
        if(in_array($action,$this->in_action, true)){
            $token = request()->header('token');
            if(empty($token)){
                throw new HttpResponseException($this->failData('请先登录',OperationErr));
            }
            $this->checkToken($token);
        }
        return true;
    }

    /**
     * 当前方法是否需要缓存
     * @return bool
     */
    public function isCache(){
        if(array_key_exists($this->action, $this->now_action_option)){//方法需要缓存
            $this->now_action_is_cache = true;
        }
        return $this->now_action_is_cache;
    }

    /**
     * 获取缓存名称
     * @return string
     */
    public function getCacheName(){
        $cacheName = $this->root.'/'.$this->controller . '/' . $this->action;
        $data = input('');
        $cacheName .= '/' . http_build_query($data);
        return $cacheName;
    }

    /**
     * 获取指定方法缓存
     * @return bool
     */
    public function getPublicCache(){
        if($this->isCache()){//方法需要缓存
            $cacheName = $this->getCacheName();
            if(cache($cacheName)){
                throw new HttpResponseException(cache($cacheName));
            }
        }
        return true;
    }

    /**
     * 设置指定方法缓存
     * @param $data
     * @return bool
     */
    public function setPublicCache($data){
        if($this->isCache()){//方法需要缓存
            $cacheName = $this->getCacheName();
            if(!cache($cacheName)){
                cache($cacheName,$data,$this->now_action_option[$this->action]);
            }
        }
        return true;
    }

    /**
     * 接口成功返回
     * @param $data
     * @param int $code
     * @return \think\response\Json
     */
    public function successData ($data=true,$code=200)
    {
        $res = json([
            'data' => $data,
            'code' => $code
        ]);
        $this->setPublicCache($res);
        return $res;
    }

    /**
     * 接口请求失败
     * @param int $code
     * @param string $msg
     * @return \think\response\Json
     */
    public function failData($msg='接口报错提示',$code=Err)
    {
        return json([
            'code' => $code,
            'msg'  => $msg
        ]);
    }

    /**
     * 直接抛出错误
     * @param string $msg
     * @param int $code
     */
    public function errorData($msg='接口报错提示',$code=Err){
        throw new HttpResponseException($this->failData($msg,$code));
    }

    /**
     * 生成token(使用微信签名算法)
     * @param $user
     * @param $is_check bool 是否是验证token
     * @return mixed
     */
    public function getToken($user,$is_check = false)
    {
        // 开始生成token并缓存
        $user_admin = config('app.api_config');
        $time = time();
        $user['end_time'] = $time + $user_admin['expire'];
        if($is_check){
            $user['end_time'] = cache("user_token_".$user['id']."_end_time");
        }
        $data = [
            'end_time'=>$user['end_time'],
            'id'=>$user['id']
        ];
        ksort($data);
        $string = http_build_query($data);
        $string = urldecode($string).'&key='.$user_admin['token_key'];
        $sign = md5($string);
        $user['sign'] = strtoupper($sign);

        if(!$is_check){
            // 清除上次登录缓存
            cache(cache("user_token_".$user['id']),null);
            cache("user_token_".$user['id'],null);
            cache("user_token_".$user['id']."_end_time",null);
            cache($user['sign'],$user,['expire'=>$user_admin['expire']]);
            cache("user_token_".$user['id'],$user['sign'],['expire'=>$user_admin['expire']]);
            cache("user_token_".$user['id']."_end_time",$user['end_time'],['expire'=>$user_admin['expire']]);
        }
        return $user;
    }

    /**
     * 验证token
     * @param $token
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkToken($token)
    {
        if(!isset($token) || empty($token))
        {
            throw new HttpResponseException($this->failData('非法请求',OperationErr));
        }

        $user_token = cache($token);
        if(!$user_token){
            throw new HttpResponseException($this->failData('token验证失败',OperationErr));
        }
        $user = User::where('openid',$user_token['openid'])->find();
        $token = $this->getToken($user->toArray(),true);
        $time = time();

        if($token['sign'] !== $user_token['sign']){
            throw new HttpResponseException($this->failData('token验证失败',OperationErr));
        }

        if($time > $user_token['end_time']){
            throw new HttpResponseException($this->failData('登录超时,请重新登录',OperationErr));
        }

        $this->user = $token;
        return true;
    }
}

2.修改

搜索:$user_admin = config('app.api_config');
$user_admin说明:

$user_admin = [
    'expire'=>7200,    //token缓存的时间
    'token_key'=>1111    //token缓存的密码
]

 搜索:$user = User::where('openid',$user_token['openid'])->find();
把这条查询的数据修改成自己表的查询数据

OK,完成

3.使用方式

<?php

namespace app\controller;

class Index extends ApiBase
{
    // a方法需要验证登录,注意这个变量里面全小写
    protected $in_action = [
        'a'
    ];

    public function a(){

    }

    public function b(){

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值