chengkun
2025-09-15 17e42d4e0fa95c7af0173be4ef4768eeb6090d5f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
 
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
 
namespace think\model\concern;
 
use ReflectionClass;
use think\db\exception\ModelEventException;
use think\helper\Str;
 
/**
 * 模型事件处理.
 */
trait ModelEvent
{
    /**
     * Event对象
     *
     * @var object
     */
    protected static $event;
 
    /**
     * 是否需要事件响应.
     *
     * @var bool
     */
    protected $withEvent = true;
 
    /**
     * 事件观察者.
     *
     * @var string
     */
    protected $eventObserver;
 
    /**
     * 设置Event对象
     *
     * @param object $event Event对象
     *
     * @return void
     */
    public static function setEvent($event)
    {
        self::$event = $event;
    }
 
    /**
     * 当前操作的事件响应.
     *
     * @param bool $event 是否需要事件响应
     *
     * @return $this
     */
    public function withEvent(bool $event)
    {
        $this->withEvent = $event;
 
        return $this;
    }
 
    /**
     * 触发事件.
     *
     * @param string $event 事件名
     *
     * @return bool
     */
    protected function trigger(string $event): bool
    {
        if (!$this->withEvent) {
            return true;
        }
 
        $call = 'on' . Str::studly($event);
 
        try {
            if ($this->eventObserver) {
                $reflect  = new ReflectionClass($this->eventObserver);
                $observer = $reflect->newinstance();
            } else {
                $observer = static::class;
            }
 
            if (method_exists($observer, $call)) {
                $result = $this->invoke([$observer, $call], [$this]);
            } elseif (is_object(self::$event) && method_exists(self::$event, 'trigger')) {
                $result = self::$event->trigger(static::class . '.' . $event, $this);
                $result = empty($result) ? true : end($result);
            } else {
                $result = true;
            }
 
            return !(false === $result);
        } catch (ModelEventException $e) {
            return false;
        }
    }
}