Files
mini_tp/app/api/controller/BaseController.php
T
2026-04-17 07:48:44 +00:00

146 lines
3.4 KiB
PHP

<?php
declare (strict_types = 1);
namespace app\api\controller;
use think\App;
use think\exception\ValidateException;
use think\Validate;
/**
* API 基础控制器
*/
abstract class BaseController
{
/**
* Request实例
* @var \think\Request
*/
protected $request;
/**
* 应用实例
* @var \think\App
*/
protected $app;
/**
* 构造方法
* @access public
* @param App $app 应用对象
*/
public function __construct(App $app)
{
$this->app = $app;
$this->request = $this->app->request;
// 控制器初始化
$this->initialize();
}
// 初始化
protected function initialize()
{}
/**
* 获取当前登录用户载荷。
*
* 说明:
* - 登录态由路由中间件 `\app\api\middleware\Auth` 统一校验
* - 控制器只负责读取中间件已经注入的用户信息
*
* @return array
*/
protected function getLoginPayload(): array
{
$payload = $this->request->middleware('payload', []);
if (empty($payload['userid'])) {
throw new \RuntimeException('未登录', 401);
}
return $payload;
}
/**
* 获取当前登录用户 ID。
*
* @return int
*/
protected function getLoginUserId(): int
{
return (int) $this->getLoginPayload()['userid'];
}
/**
* 成功响应
* @param mixed $data 返回数据
* @param string $message 提示信息
* @param int $code 状态码
* @return \think\response\Json
*/
protected function success($data = [], string $message = 'success', int $code = 200)
{
return json([
'code' => $code,
'msg' => $message,
'data' => $data,
'time' => time(),
]);
}
/**
* 失败响应
* @param string $message 提示信息
* @param int $code 状态码
* @param mixed $data 返回数据
* @return \think\response\Json
*/
protected function error(string $message = 'error', int $code = 400, $data = [])
{
return json([
'code' => $code,
'msg' => $message,
'data' => $data,
'time' => time(),
]);
}
/**
* 验证数据
* @access protected
* @param array $data 数据
* @param string|array $validate 验证器名或者验证规则数组
* @param array $message 提示信息
* @param bool $batch 是否批量验证
* @return array|string|true
* @throws ValidateException
*/
protected function validate(array $data, $validate, array $message = [], bool $batch = false)
{
if (is_array($validate)) {
$v = new Validate();
$v->rule($validate);
} else {
if (strpos($validate, '.')) {
// 支持场景
[$validate, $scene] = explode('.', $validate);
}
$class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
$v = new $class();
if (!empty($scene)) {
$v->scene($scene);
}
}
$v->message($message);
// 是否批量验证
if ($batch || $this->request->isBatchValidate()) {
$v->batch(true);
}
return $v->failException(true)->check($data);
}
}