初始化项目

This commit is contained in:
2025-05-12 00:19:35 +08:00
parent f6e4638ee6
commit fc327e9f48
27 changed files with 11107 additions and 29 deletions

View File

@@ -0,0 +1,23 @@
<?php
namespace App\BaseApp;
class BaseClient
{
private static mixed $_instance;
/**
* 获取实例
* @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];
}
}

169
app/BaseApp/BaseController.php Executable file
View File

@@ -0,0 +1,169 @@
<?php
namespace App\BaseApp;
use App\Service\common\UtilsService;
use Exception;
use Illuminate\Http\JsonResponse;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class BaseController
{
protected array $insertField = [];
protected array $notRequest = [];
protected array $updateField = [];
protected $service;
public function __construct()
{
}
/**
* 获取列表
* @Method GET
* @return JsonResponse
* @throws Exception
*/
public function list(): JsonResponse
{
return jok(
$this->service->list(),
'列表获取成功'
);
}
/**
* 获取下拉列表
* @Method GET
* @return mixed
* @throws Exception
*/
public function option(): mixed
{
return jok(
$this->service->option(),
'列表获取成功'
);
}
/**
* 获取详情
*
* @Method GET
* @return JsonResponse
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception
*/
public function detail(): JsonResponse
{
$id = request()->get('id');
if (empty($id)) UtilsService::getInstance()->notFound('参数错误');
return jok(
$this->service->detail($id),
'详情获取成功'
);
}
/**
* 创建
*
* @Method POST
* @return JsonResponse
* @throws Exception
*/
public function create(): JsonResponse
{
$params = $this->checkRequiredFields(request()->post());
return jok(
$this->service->create($params),
'创建成功'
);
}
/**
* 更新
*
* @Method POST
* @return JsonResponse
* @throws Exception
*/
public function update(): JsonResponse
{
$params = $this->checkRequiredFields(request()->post(), 'update');
$id = $params['id'];
unset($params['id']);
return jok(
$this->service->update($id, $params),
'更新成功'
);
}
/**
* 删除
*
* @Method POST
* @return JsonResponse
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception
*/
public function delete(): JsonResponse
{
$id = request()->post('ids');
if (empty($id)) UtilsService::getInstance()->notFound('参数错误');
return jok(
$this->service->delete($id),
'删除成功'
);
}
/**
* 检查必填字段
*
* @Method NO
* @param array $data
* @param string $checkType
* @param bool $throw
* @return array
* @throws Exception
*/
public function checkRequiredFields(array $data = [], string $checkType = 'create', bool $throw = true): array
{
$checkFields = $checkType == 'create' ? $this->insertField : $this->updateField;
if (!empty($this->notRequest)) {
$checkFields = array_merge($this->notRequest, $checkFields);
}
$requiredFields = [];
$result = [];
foreach ($checkFields as $fieldName) {
$checkValue = $data[$fieldName] ?? '';
if (is_array($checkValue) && !empty($checkValue)) {
$result[$fieldName] = $checkValue;
} else {
if (mb_strlen(strval($checkValue)) <= 0 && !in_array($fieldName, $this->notRequest)) {
$requiredFields[] = $fieldName;
} else {
if (!empty($checkValue) || $checkValue === 0) {
$result[$fieldName] = $checkValue;
}
}
}
}
if ($throw && $requiredFields) {
UtilsService::getInstance()->notFound('未填写的字段: ' . implode(',', $requiredFields));
}
if (!empty($requiredFields)) {
return $requiredFields;
}
return $result;
}
}

26
app/BaseApp/BaseModel.php Executable file
View File

@@ -0,0 +1,26 @@
<?php
namespace App\BaseApp;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model
{
protected $connection = 'mysql';
public $timestamps = false;
public function getCreatedAtAttribute($value): string
{
if (empty($value)) {
return '';
}
return date('Y-m-d H:i:s', $value);
}
// 定义访问器,将 created_at 字段格式化为指定格式
public function getUpdatedAtAttribute($value): string
{
if (empty($value)) {
return '';
}
return date('Y-m-d H:i:s', $value);
}
}

322
app/BaseApp/BaseService.php Executable file
View File

@@ -0,0 +1,322 @@
<?php
namespace App\BaseApp;
use App\Models\UserModel;
use App\Service\common\JWTService;
use App\Service\common\UtilsService;
use Exception;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class BaseService
{
/**
* @var mixed 单例实例,确保该类只有一个全局实例
*/
protected 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;
/**
* @var bool 是否需要验证用户权限
*/
protected bool $isAuth = true;
/**
* @var array 查询的字段
*/
protected array $selectField = ['*'];
/**
* @var array 查询条件Between
*/
protected array $whereBetween = [];
/**
* @var array 排序条件
*/
protected array $orderBy = [
'name' => 'id',
'sort' => 'desc',
];
/**
* @var array 查询条件
*/
protected array $where = [
['deleted_at', '=', 0]
];
/**
* @var array 查询条件In
*/
protected array $whereIn = [];
/**
* @var array 下拉列表字段
*/
protected array $optionField = ['id', 'name'];
/**
* @var array 下拉列表字段
*/
protected array $queryField = [];
/**
* @var array 关联加载
*/
protected array $with = [];
/**
* @var string 时间字段
*/
protected string $timeField = 'created_at';
public function __construct()
{
if ($this->isAuth) {
$this->userInfo = JWTService::getInstance()->getToken()->getUserInfo();
$this->userId = $this->userInfo['id'] ?? 0;
} else {
try {
$this->userInfo = JWTService::getInstance()->getToken()->getUserInfo();
$this->userId = $this->userInfo['id'] ?? 0;
} catch (Exception $e) {
$this->userId = 0;
}
}
$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];
}
/**
* 获取列表数据
*
* 本函数负责根据设定的条件,从数据库中查询并返回分页后的数据列表
* 它会根据空值条件动态地修改查询,以实现灵活的查询需求
*
* @return array 返回包含分页信息和数据列表的数组
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function getPageList($isArr = true, $isGetWhere = true): array
{
// 初始化查询条件
if ($isGetWhere === true) $this->getWhere();
// 获取范围查询条件
$searchTime = request()->get('search_time');
if (!empty($searchTime)) {
$this->getWhereBetween($searchTime);
}
// 执行数据库查询,根据条件动态构建查询语句
$result = $this->model::when(!empty($this->with), function ($query) {
// 如果关联加载条件存在,则添加关联加载
$query->with($this->with);
})
->when(!empty($this->where), function ($query) {
// 如果查询条件存在,则添加查询条件
$query->where($this->where);
})
->when(!empty($this->whereIn), function ($query) {
// 如果查询条件存在,则添加查询条件
$query->whereIn($this->whereIn[0], $this->whereIn[1]);
})
->when(!empty($this->whereBetween), function ($query) {
// 如果范围查询条件存在,则添加范围查询
$query->whereBetween($this->whereBetween[0], $this->whereBetween[1]);
})
->when(!empty($this->orderBy), function ($query) {
// 如果排序条件存在,则添加排序条件
$query->orderBy($this->orderBy['name'], $this->orderBy['sort']);
})
->select($this->selectField)
// 执行分页查询每页返回10条记录
->paginate(request()->get('pageSize', 20));
if ($isArr === true) {
$result = $result->toArray() ?? [];
// 返回分页信息和数据列表
return [
'page' => $result['current_page'],
'size' => $result['per_page'],
'page_count' => $result['last_page'],
'total' => $result['total'],
'items' => $result['data'],
];
}
// 返回分页信息和数据列表
return [
'page' => $result->currentPage(),
'size' => $result->perPage(),
'page_count' => $result->lastPage(),
'total' => $result->total(),
'items' => $result->items(),
];
}
/**
* 获取下拉列表数据
* @return mixed
*/
public function getOption(): mixed
{
$this->getWhere();
return $this->model::when(!empty($this->where), function ($query) {
$query->where($this->where);
})->when(!empty($this->whereIn), function ($query) {
$query->where($this->whereIn[0], $this->whereIn[1]);
})->orderBy($this->orderBy['name'], $this->orderBy['sort'])->get($this->optionField);
}
/**
* 详情
*
* @param $id
* @return mixed
* @throws Exception
*/
public function getDetail($id): mixed
{
$info = $this->model::with($this->with)->select($this->selectField)->find($id);
if (empty($info)) {
return $this->utils->notFound('数据不存在');
}
return $info;
}
/**
* 新增
* @param $params
* @return mixed
*/
public function insert($params): mixed
{
if (!array_key_exists('created_at', $params)) {
$params['created_at'] = time();
}
// return $this->model::insertGetId($this->utils->truncatedOss($params));
return $this->model::insertGetId($params);
}
/**
* 编辑
* @param $id
* @param $params
* @return mixed
* @throws Exception
*/
public function save($id, $params): mixed
{
if (empty(trim($id))) {
$this->utils->errorThrow('参数错误');
}
$this->where[] = ['id', '=', $id];
// 软删除
$info = $this->model::where($this->where)->first();
if (empty($info)) {
return $this->utils->notFound('数据不存在');
}
if (!array_key_exists('updated_at', $params)) {
$params['updated_at'] = time();
}
// return $this->model::where('id', $id)->update($this->utils->truncatedOss($params));
return $this->model::where('id', $id)->update($params);
}
/**
* 删除
*
* @param $id
* @return mixed|true
* @throws Exception
*/
public function del($id): mixed
{
// 软删除
$info = $this->model::whereIn('id', $id)->get(['id']);
if (empty($info)) {
return $this->utils->notFound('数据不存在');
}
if ($this->model::whereIn('id', $id)->update([
'deleted_at' => time(),
'updated_at' => time()
])) {
return true;
} else {
$this->utils->errorThrow('删除失败');
}
}
/**
* 获取查询条件
* @return void
*/
protected function getWhere(): void
{
$query = request()->query();
if (!empty($this->queryField)) {
foreach ($this->queryField as $key => $value) {
if (in_array($key, array_keys($query))) {
if (!empty($query[$key] ?? '') || $query[$key] == '0') {
switch ($value) {
case '=':
$this->where[] = [$key, $value, $query[$key]];
break;
case 'like':
$this->where[] = [$key, $value, '%' . $query[$key] . '%'];
break;
default:
break;
}
}
}
}
}
}
/**
* 获取时间范围查询条件
* @param $searchTime
* @return void
*/
protected function getWhereBetween($searchTime): void
{
$this->whereBetween = [$this->timeField, [strtotime($searchTime[0] ?? date('Y-m-01 00:00:00')), strtotime(date('Y-m-d 23:59:59', strtotime($searchTime[1])) ?? date('Y-m-d 23:59:59'))]];
}
}