Files
hyperf_data/extend/Aether/PHP/Hyperf/AbstractService.php
阿不叮咚 edd4effc95 封装优化
2025-09-24 15:38:44 +08:00

147 lines
3.6 KiB
PHP

<?php
declare(strict_types=1);
namespace Aether;
use App\Exception\BusinessException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;
abstract class AbstractService
{
#[Inject]
protected LoggerFactory $loggerFactory;
/**
* @var LoggerInterface
*/
protected LoggerInterface $logger;
public function __construct()
{
$this->logger = $this->loggerFactory->get($this->getLoggerName());
}
/**
* 获取资源列表
*/
public function list(array $params = []): array
{
$this->validateQuery($params);
return $this->getModel()::query()
->when(isset($params['page']), function ($query) use ($params) {
$page = (int)($params['page'] ?? 1);
$size = (int)($params['size'] ?? 20);
return $query->forPage($page, $size);
})
->get()
->toArray();
}
/**
* 获取资源详情
*/
public function detail(int $id): array
{
$model = $this->getModel()::find($id);
if (!$model) {
throw new BusinessException(404, '资源不存在');
}
return $model->toArray();
}
/**
* 创建资源
*/
public function create(array $data): int
{
$this->validateCreate($data);
$model = $this->getModel()::create($data);
$this->logger->info('资源创建成功', ['id' => $model->id, 'data' => $data]);
return $model->id;
}
/**
* 更新资源
*/
public function update(int $id, array $data): bool
{
$this->validateUpdate($data);
$model = $this->getModel()::find($id);
if (!$model) {
throw new BusinessException(404, '资源不存在');
}
$result = $model->update($data);
$this->logger->info('资源更新成功', ['id' => $id, 'data' => $data]);
return $result;
}
/**
* 删除资源
*/
public function delete(int $id): bool
{
$model = $this->getModel()::find($id);
if (!$model) {
throw new BusinessException(404, '资源不存在');
}
$result = $model->delete();
$this->logger->info('资源删除成功', ['id' => $id]);
return $result;
}
/**
* 验证查询参数
*/
protected function validateQuery(array $params): void
{
$validator = $this->getValidator()->scene('query', $params);
if ($validator->fails()) {
throw new BusinessException(400, $validator->errors()->first());
}
}
/**
* 验证创建参数
*/
protected function validateCreate(array $data): void
{
$validator = $this->getValidator()->scene('create', $data);
if ($validator->fails()) {
throw new BusinessException(400, $validator->errors()->first());
}
}
/**
* 验证更新参数
*/
protected function validateUpdate(array $data): void
{
$validator = $this->getValidator()->scene('update', $data);
if ($validator->fails()) {
throw new BusinessException(400, $validator->errors()->first());
}
}
/**
* 获取日志名称
*/
protected function getLoggerName(): string
{
return strtolower((new \ReflectionClass($this))->getShortName());
}
/**
* 获取对应的模型类
* @return AbstractModel
*/
abstract protected function getModel(): AbstractModel;
/**
* 获取对应的验证器类
* @return AbstractValidator
*/
abstract protected function getValidator(): AbstractValidator;
}