tp/app/index/BaseController.php
2026-03-10 22:24:06 +08:00

149 lines
3.5 KiB
PHP

<?php
declare(strict_types=1);
// 关键修正:命名空间对应控制器目录
namespace app\index;
use think\App;
use think\exception\ValidateException;
use think\Validate;
use think\Request;
use think\facade\Db;
// 在控制器方法中添加
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
/**
* 控制器基础类
*/
abstract class BaseController
{
/**
* Request实例
* @var Request
*/
protected $request;
/**
* 应用实例
* @var App
*/
protected $app;
/**
* 是否批量验证
* @var bool
*/
protected $batchValidate = false;
/**
* 控制器中间件
* @var array
*/
protected $middleware = [];
/**
* 当前租户ID
* @var int
*/
protected $tenantId = 0;
/**
* 构造方法
* @access public
* @param App $app 应用对象
*/
public function __construct(App $app)
{
$this->app = $app;
$this->request = $this->app->request;
// 控制器初始化
$this->initialize();
}
// 初始化
protected function initialize()
{
// 自动检测并设置租户ID
$this->initTenantId();
}
/**
* 初始化租户ID
* 优先从 Referer 获取来源域名,否则使用当前访问域名
* 从 mete_tenant_domain 表查询对应的 tid
*/
protected function initTenantId(): void
{
// 优先从 Referer 获取来源域名(跨域调用场景)
$referer = $this->request->header('Referer');
if ($referer) {
$host = parse_url($referer, PHP_URL_HOST);
} else {
// 否则使用当前访问域名
$host = $this->request->host(true);
}
// 查询域名对应的租户ID
$tenantDomain = Db::name('mete_tenant_domain')
->where('full_domain', $host)
->where('status', 1)
->whereNull('delete_time')
->find();
if ($tenantDomain) {
$this->tenantId = (int)$tenantDomain['tid'];
}
}
/**
* 获取当前租户ID
* @return int
*/
protected function getTenantId(): int
{
return $this->tenantId;
}
/**
* 验证数据
* @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, string|array $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->batchValidate) {
$v->batch(true);
}
return $v->failException(true)->check($data);
}
}