美文网首页tp5.1PHP
ThinkPHP5.1构建Restful风格API

ThinkPHP5.1构建Restful风格API

作者: 无处裸奔 | 来源:发表于2019-07-08 08:39 被阅读0次

下载安装composer

composer使用国内镜像

composer config -g repo.packagist composer https://packagist.phpcomposer.com

通过composer安装ThinkPHP5.1

composer create-project topthink/think 项目名称

通过composer安装jwt

composer require firebase/php-jwt

ThinkPHP5.1配置

// config/app.php
<?php
return [
    // 开启调试
    'app_debug'              => true,
    // 禁止访问模块
    'deny_module_list'       => [],   
];
// config/log.php

<?php
return [
    'type'        => 'File',
    'path'        => '../logs/',
    'level'       => [],
    'single'      => false,
    'apart_level' => [],
    'max_files'   => 0,
    'close'       => false,
    'json'        => true,
];
// application/common.php
// 此文件的意义,个人理解是定义全局变量和全局函数的

<?php
const ERRNO_MAP = [
    'OK'         => '成功',
    'DBERR'      => '数据库查询错误',
    'NODATA'     => '无数据',
    'DATAEXIST'  => '数据已存在',
    'DATAERR'    => '数据错误',
    'SESSIONERR' => '用户未登录',
    'LOGINERR'   => '用户登录失败',
    'PARAMERR'   => '参数错误',
    'USERERR'    => '用户不存在或未激活',
    'ROLEERR'    => '用户身份错误',
    'PWDERR'     => '密码错误',
    'REQERR'     => '非法请求或请求次数受限',
    'IPERR'      => 'IP受限',
    'THIRDERR'   => '第三方系统错误',
    'IOERR'      => '文件读写错误',
    'SERVERERR'  => '内部错误',
    'UNKOWNERR'  => '未知错误',
];
const ERRNO = [
    'OK'         => '0',
    'DBERR'      => '4001',
    'NODATA'     => '4002',
    'DATAEXIST'  => '4003',
    'DATAERR'    => '4004',
    'SESSIONERR' => '4101',
    'LOGINERR'   => '4102',
    'PARAMERR'   => '4103',
    'USERERR'    => '4104',
    'ROLEERR'    => '4105',
    'PWDERR'     => '4106',
    'REQERR'     => '4201',
    'IPERR'      => '4202',
    'THIRDERR'   => '4301',
    'IOERR'      => '4302',
    'SERVERERR'  => '4500',
    'UNKOWNERR'  => '4501',
];

// 向前端返回JSON数据
function ajaxReturn() {
    // 形参个数
    $args_num = func_num_args();
    // 形参列表
    $args = func_get_args();
    if (1 === $args_num) {
        return \json([
            'errno' => ERRNO['OK'],
            'msg'   => '成功',
            'data'  => $args[0]]);
    }
    if (2 === $args_num) {
        return \json([
            'errno' => $args[0],
            'msg'   => $args[1]]);
    }
    if (3 === $args_num) {
        return \json([
            'errno' => $args[0],
            'msg'   => $args[1],
            'data'  => $args[2]]);
    }
    throw new Exception("Error The number of parameters can be one or two or three");
}

use \Firebase\JWT\JWT;
// 设置JWT
function setJWT($data) {
    $jwt   = new JWT();
    $token = array(
        // "iss"  => "http://example.org", // 签发者
        // "aud"  => "http://example.com", // 认证者
        'iat'  => time(), // 签发时间
        'nbf'  => time(), // 生效时间
        'exp'  => (time() + 60 * 60 * 24 * 7), // 过期时间  7天后的时间戳
        'data' => $data,
    );
    $jwt = $jwt::encode($token, \config('jwt_key'), 'HS256');
    return $jwt;
}
// 获取JWT内容
function getJWT($token) {
    $jwt  = new JWT();
    $data = null;
    try {
        $jwt_data = $jwt::decode($token, \config('jwt_key'), array('HS256'));
        $data     = (array) ($jwt_data->data);
    } catch (\Throwable $e) {
        Log::write($e->getMessage(), 'error');
        return null;
    }
    return $data;
}
// application/common/controller/Common.php

<?php
namespace app\common\controller;
class Common {
    public function miss() {
        return \json([
            'errno' => \ERRNO['PARAMERR'],
            'msg'   => '访问接口不存在或参数错误']);
    }
}

// application/common/controller/Authen.php

<?php
namespace app\common\controller;

use app\common\controller\Common;

class Authen extends Common {
    // 用户信息
    protected $user_info;
    public function initialize() {
        $token = \input('server.http_token');
        // 验证是否登录
        if (is_null($token)) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode([
                'code'  => ERRNO['SESSIONERR'],
                'error' => '用户未登陆']));
        }
        // 验证登录是否过期
        $user_info = \getJWT($token);
        if (is_null($user_info)) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode([
                'code'  => ERRNO['SESSIONERR'],
                'error' => '登录已过期']));
        }
        // 存储用户信息
        $this->user_info = $user_info;
    }
}
// application/test[应用名称]/config/database.php

<?php
return [
    'type'            => 'mysql',
    'hostname'        => '127.0.0.1',
    'database'        => 'test',
    'username'        => 'root',
    'password'        => 'root',
    'hostport'        => '3306',
];
// application/test[应用名称]/controller/v1/Teacher.php

<?php
namespace app\test\controller\v1;
// 不需要认证的话继承Common
use app\common\controller\Common;

// 需要登录验证的继承Authen
// use app\common\controller\Authen;
use Log;

class Teacher extends Common {
    // 查 getTest
    // 增 postTest
    // 改 putTest
    // 删 deleteTest
    public function getStudents() {
        return \ajaxReturn(ERRNO['OK'],'查询成功',['list'=>[]]);
    }
}
// route/route.php

<?php
// 定义miss路由
Route::miss('common/Common/miss');
// route/test[应用名称].php

<?php
Route::group('test/v1.0', function () {
    Route::group('teacher', function () {
        // /test/v1.0/teacher/students
        Route::get('students', 'getStudents');
    })->prefix('test/v1.teacher/');
})
    ->ext(false)
    ->header('Access-Control-Allow-Headers', 'token')
    ->allowCrossDomain()
    ->pattern(['id' => '\d+']);

部署到linux上的问题

// 删除.user.ini文件
chattr -i ~/public/.user.ini
rm -f ~/public/.user.ini

// 改变目录权限
chmod -R 777 ~

相关文章

网友评论

    本文标题:ThinkPHP5.1构建Restful风格API

    本文链接:https://www.haomeiwen.com/subject/qwhnhctx.html