1、配置
开启调试
自定义路由
数据库
2、框架初始化
定义基类返回数据
php think make:controller BaseController --plain
控制器返回数据方法
<?php
namespace app\common\controller;
use think\Controller;
class BaseController extends Controller
{
// 返回数据
public static function showResCode($msg = '',$data=[],$code = 200){
$res = [
'msg' => $msg,
'data' => $data
];
return json($res, $code);
}
// 返回不带数据
public static function showResWithoutCode($msg = '', $code = 200){
return self::showResCode($msg, [], $code);
}
}
自定义异常
异常类:BaseException
<?php
namespace app\lib\exception;
use Exception;
class BaseException extends Exception{
public $code;
public $msg;
public function __construct($msg = '请求失败', $code= 400){
$this->code = $code;
$this->msg = $msg;
}
}
异常处理:ExceptionHandle
<?php
namespace app\lib\exception;
use Exception;
use think\exception\Handle;
class ExceptionHandle extends Handle{
public $code;
public $msg;
public function render(Exception $e)
{
if ($e instanceof BaseException) {
$this->code = $e->code;
$this->msg = $e->msg;
} else {
// 调试开启(开发环境下),抛出非自定义异常让父类解决
if (config('app.app_debug')) return parent::render($e);
$this->code = 500;
$this->msg = '服务器异常';
}
$res = [
'msg' => $this->msg,
'code' => $this->code,
];
return json($res, $this->code);
}
}
配置文件修改:app.php最后一行
// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle' => '\app\lib\exception\ExceptionHandle',
测试:
自定义验证器基类
php think make:validate BaseValidate
BaseValidate.php
<?php
namespace app\common\validate;
use app\lib\exception\BaseException;
use think\Validate;
class BaseValidate extends Validate
{
public function goCheck($scene = '')
{
// 拿到请求参数
$params = request()->param();
// 场景为空就全部验证,有值就按照场景定义验证
$validate_res = empty($scene) ? $this->check($params) : $this->scene($scene)->check($params);
if ($validate_res) throw new BaseException($this->getError());
return true;
}
}
1 游客 2025-09-01 11:27 回复
1
1 游客 2025-09-01 12:09 回复
1
@@f3Uw3 游客 2025-09-01 12:11 回复
1
1 游客 2025-09-01 12:13 回复
1
1 游客 2025-09-01 12:14 回复
-1 OR 2+773-773-1=0+0+0+1