* * 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; // 重新抛出捕获的异常 } } }