Skip to content

Commit 9165c2b

Browse files
author
lidanyang
committed
add transaction annotation
1 parent 7a7627e commit 9165c2b

2 files changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
6+
namespace CC\Hyperf\Common\Aspects\Annotations;
7+
8+
9+
use Hyperf\Di\Annotation\AbstractAnnotation;
10+
11+
/**
12+
* @Annotation
13+
* @Target({"METHOD","CLASS"})
14+
*/
15+
class Transactional extends AbstractAnnotation
16+
{
17+
18+
}

src/Aspects/TransactionAspect.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
6+
namespace CC\Hyperf\Common\Aspects;
7+
8+
use Hyperf\DbConnection\Db;
9+
use Hyperf\Di\Annotation\Aspect;
10+
use Hyperf\Di\Aop\AbstractAspect;
11+
use Hyperf\Di\Aop\ProceedingJoinPoint;
12+
use CC\Hyperf\Common\Aspects\Annotations\Transactional;
13+
14+
/**
15+
* 自动事务注解
16+
* @Aspect
17+
*/
18+
class TransactionAspect extends AbstractAspect
19+
{
20+
21+
public $annotations = [
22+
Transactional::class,
23+
];
24+
25+
/**
26+
* @inheritDoc
27+
* @throws \Throwable
28+
*/
29+
public function process(ProceedingJoinPoint $proceedingJoinPoint)
30+
{
31+
try {
32+
Db::beginTransaction();
33+
$result = $proceedingJoinPoint->process();
34+
Db::commit();
35+
return $result;
36+
} catch (\Throwable $e) {
37+
Db::rollBack();
38+
throw $e;
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)