Files
wh-api/app/Aspect/TransactionalAspect.php
ykxiao 0b2299c427
Some checks failed
Build Docker / build (push) Has been cancelled
协程版仓库后端项目
2025-07-08 14:59:47 +08:00

56 lines
1.4 KiB
PHP
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
/**
* Author: ykxiao
* Date: 2025/6/5
* Time: 下午11:50
* Description:
*
* (c) ykxiao <yk_9001@hotmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
declare(strict_types=1);
namespace App\Aspect;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Throwable;
#[Aspect]
class TransactionalAspect extends AbstractAspect
{
public array $classes = [
'App\Controller\*',
];
public array $annotations = [
];
/**
* 处理方法执行过程通过AOP的方式对方法执行进行事务控制。
*
* @param ProceedingJoinPoint $proceedingJoinPoint AOP中的连接点对象代表正在执行的方法
* @return mixed 返回执行方法的结果
* @throws Throwable 如果执行过程中发生异常,则抛出
*/
public function process(ProceedingJoinPoint $proceedingJoinPoint): mixed
{
Db::beginTransaction(); // 开始事务
try {
$result = $proceedingJoinPoint->process(); // 执行目标方法
Db::commit(); // 方法执行成功,提交事务
return $result;
} catch (Throwable $e) {
Db::rollback(); // 发生异常,回滚事务
throw $e; // 重新抛出捕获的异常
}
}
}