基类和工具类
This commit is contained in:
70
app/BaseApp/BaseService.php
Executable file
70
app/BaseApp/BaseService.php
Executable file
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\BaseApp;
|
||||
|
||||
use App\Models\UserModel;
|
||||
use App\Service\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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user