Skip to content

Commit 2254287

Browse files
committed
模型增加事件观察支持
1 parent 88509f0 commit 2254287

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

src/model/concern/ModelEvent.php

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
namespace think\model\concern;
1515

16+
use ReflectionClass;
1617
use think\db\exception\ModelEventException;
1718
use think\helper\Str;
1819

@@ -35,6 +36,13 @@ trait ModelEvent
3536
*/
3637
protected $withEvent = true;
3738

39+
/**
40+
* 事件观察者.
41+
*
42+
* @var string
43+
*/
44+
protected $eventObserver;
45+
3846
/**
3947
* 设置Event对象
4048
*
@@ -77,10 +85,17 @@ protected function trigger(string $event): bool
7785
$call = 'on' . Str::studly($event);
7886

7987
try {
80-
if (method_exists(static::class, $call)) {
81-
$result = call_user_func([static::class, $call], $this);
88+
if ($this->eventObserver) {
89+
$reflect = new ReflectionClass($this->eventObserver);
90+
$observer = $reflect->newinstance();
91+
} else {
92+
$observer = static::class;
93+
}
94+
95+
if (method_exists($observer, $call)) {
96+
$result = call_user_func([$observer, $call], $this);
8297
} elseif (is_object(self::$event) && method_exists(self::$event, 'trigger')) {
83-
$result = self::$event->trigger('model.' . static::class . '.' . $event, $this);
98+
$result = self::$event->trigger(static::class . '.' . $event, $this);
8499
$result = empty($result) ? true : end($result);
85100
} else {
86101
$result = true;

0 commit comments

Comments
 (0)