Files
spa-api/app/BaseApp/BaseService.php
2025-05-05 09:44:50 +08:00

71 lines
1.6 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\BaseApp;
use App\Models\UserModel;
use App\Service\common\UtilsService;
class BaseService
{
/**
* @var mixed 单例实例,确保该类只有一个全局实例
*/
private static mixed $_instance;
/**
* @var object 工具类对象,用于提供通用的功能方法
*/
protected object $utils;
/**
* @var int 用户ID默认值为0表示未登录状态
*/
protected int $userId = 0;
/**
* @var array 用户信息
*/
protected array $userInfo = [];
/**
* @var object 数据模型对象,用于数据库操作
*/
protected $model;
protected $isAuth = true;
public function __construct()
{
if ($this->isAuth) {
// 如果是home的接口可以不执行这个方法
if (!\request()->is('api/home/*')) {
$this->authUser();
}
}
$this->utils = UtilsService::getInstance();
}
/**
* 获取实例
* @return null|static
*/
public static function getInstance(): null|static
{
$name = get_called_class();
if (!isset(self::$_instance[$name])) {
self::$_instance[$name] = new static();
}
return self::$_instance[$name];
}
private function authUser()
{
$token = \request()->header('Authorization');
$token = explode(' ', $token)[1];
$userModel = UserModel::where('session_key', $token)->first();
if (!$userModel) {
jexpire('token失效');
}
$this->userId = $userModel->id;
$this->userInfo = $userModel->toArray();
}
}