根據之前一篇文章,我們知道 Yii2 的事件分兩類,一是類級別的事件,二是實例級別的事件。類級別的事件是基於 yii\base\Event 實現,實例級別的事件是基於 yii\base\Component 實現。
今天先來看下類級別事件的實現,代碼是 yii\base\Event 類。
<?php namespace yii\base; /** * Event is the base class for all event classes. */ class Event extends Object { /** * @var string the event name. This property is set by [[Component::trigger()]] and [[trigger()]]. * Event handlers may use this property to check what event it is handling. * 事件的名字 */ public $name; /** * @var object the sender of this event. If not set, this property will be * set as the object whose "trigger()" method is called. * This property may also be a `null` when this event is a * class-level event which is triggered in a static context. * 觸發事件的對象 */ public $sender; /** * @var boolean whether the event is handled. Defaults to false. * When a handler sets this to be true, the event processing will stop and * ignore the rest of the uninvoked event handlers. * 記錄事件是否已被處理,當 handled 被設置為 true 時,執行到這個 event 的時候,會停止,並忽略剩下的 event */ public $handled = false; /** * @var mixed the data that is passed to [[Component::on()]] when attaching an event handler. * Note that this varies according to which event handler is currently executing. */ public $data; /** * 存儲所有的 event,因為是 static 的屬性,所有的 event 對象/類都共享這一份數據 */ private static $_events = []; /** * Attaches an event handler to a class-level event. * * When a class-level event is triggered, event handlers attached * to that class and all parent classes will be invoked. * * For example, the following code attaches an event handler to `ActiveRecord`'s * `afterInsert` event: * * ~~~ * Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) { * Yii::trace(get_class($event->sender) . ' is inserted.'); * }); * ~~~ * * The handler will be invoked for EVERY successful ActiveRecord insertion. * * For more details about how to declare an event handler, please refer to [[Component::on()]]. * * 為一個類添加事件 * * @param string $class the fully qualified class name to which the event handler needs to attach. * @param string $name the event name. * @param callable $handler the event handler. * @param mixed $data the data to be passed to the event handler when the event is triggered. * When the event handler is invoked, this data can be accessed via [[Event::data]]. * @param boolean $append whether to append new event handler to the end of the existing * handler list. If false, the new handler will be inserted at the beginning of the existing * handler list. * @see off() */ public static function on($class, $name, $handler, $data = null, $append = true) { // 去掉 class 最左邊的斜槓 $class = ltrim($class, '\\'); // 如果 append 為true,就放到 $_events 中名字為 $name 的數組的最後,否則放到最前面 if ($append || empty(self::$_events[$name][$class])) { self::$_events[$name][$class][] = [$handler, $data]; } else { array_unshift(self::$_events[$name][$class], [$handler, $data]); } } /** * Detaches an event handler from a class-level event. * * This method is the opposite of [[on()]]. * * 移除一個類的事件 * * @param string $class the fully qualified class name from which the event handler needs to be detached. * @param string $name the event name. * @param callable $handler the event handler to be removed. * If it is null, all handlers attached to the named event will be removed. * @return boolean whether a handler is found and detached. * @see on() */ public static function off($class, $name, $handler = null) { $class = ltrim($class, '\\'); if (empty(self::$_events[$name][$class])) { // 不存在該事件 return false; } if ($handler === null) { // 如果 handler 為空,直接將在該類下該事件移除,即移出所有的是這個名字的事件 unset(self::$_events[$name][$class]); return true; } else { $removed = false; // 如果 $handler 不為空,循環 $_events 找到相應的 handler,只移除這個 handler 和 data 組成的數組 foreach (self::$_events[$name][$class] as $i => $event) { if ($event[0] === $handler) { unset(self::$_events[$name][$class][$i]); $removed = true; } } if ($removed) { // 移除之後,使數組重新變成一個自然數組 self::$_events[$name][$class] = array_values(self::$_events[$name][$class]); } return $removed; } } /** * Returns a value indicating whether there is any handler attached to the specified class-level event. * Note that this method will also check all parent classes to see if there is any handler attached * to the named event. * 檢測在某個類或者對象是否具有某個事件 * @param string|object $class the object or the fully qualified class name specifying the class-level event. * @param string $name the event name. * @return boolean whether there is any handler attached to the event. */ public static function hasHandlers($class, $name) { if (empty(self::$_events[$name])) { // 不存在,直接返回 return false; } if (is_object($class)) { // 如果是一個 object,就獲取其類名 $class = get_class($class); } else { // 如果是一個類名,就去掉 class 最左邊的斜槓 $class = ltrim($class, '\\'); } // 如果該類中找不到,就去父類中找,直到找到或者沒有父類了為止 do { if (!empty(self::$_events[$name][$class])) { return true; } } while (($class = get_parent_class($class)) !== false); return false; } /** * Triggers a class-level event. * This method will cause invocation of event handlers that are attached to the named event * for the specified class and all its parent classes. * 觸發某個類或者對象的某個事件 * @param string|object $class the object or the fully qualified class name specifying the class-level event. * @param string $name the event name. * @param Event $event the event parameter. If not set, a default [[Event]] object will be created. */ public static function trigger($class, $name, $event = null) { if (empty(self::$_events[$name])) { return; } if ($event === null) { // 事件不存在,就創建一個 Event 對象 $event = new static; } // 設置event對象的屬性,默認是未被處理的 $event->handled = false; $event->name = $name; if (is_object($class)) { if ($event->sender === null) { // 如果 $class 是個對象,並且是 sender 為空,就將 $class 賦給 sender,即 $class 就是觸發事件的對象 $event->sender = $class; } $class = get_class($class); } else { $class = ltrim($class, '\\'); } // 循環類的 $_event,直到遇到 $event->handled 為真或者沒有父類了為止 do { if (!empty(self::$_events[$name][$class])) { foreach (self::$_events[$name][$class] as $handler) { // 將參數賦到 event 對象的 data 屬性上 $event->data = $handler[1]; // 調用 $handler 方法 // 在方法中,可以用 $this->data 取到相應的參數 // 也可以在其中設置 $this->handled 的值,中斷後續事件的觸發 call_user_func($handler[0], $event); // 當某個 handled 被設置為 true 時,執行到這個事件的時候,會停止,並忽略剩下的事件 if ($event->handled) { return; } } } } while (($class = get_parent_class($class)) !== false); } }
通過上面代碼可以看出,類級別的 Event,其本質就是在 Event 類中的 $_events 變量中存儲事件,觸發事件的時候,只需將其取出,執行即可。
$_events裡面的數據結構大概如下:
[ 'add' => [ 'Child' => [ [function ($event) { ... }, $data], [[$object, 'handleAdd'], null], [['ChildClass', 'handleAdd'], $data], ['handleAdd', $data] ], 'ChildClass' => [ ... ] ], 'delete' => [ ... ] ]
之後講到yii\base\Component類時,我們會再來說一下實例級別的事件。
對 Yii2 源碼有興趣的同學可以關注項目 yii2-2.0.3-annotated,現在在上面已經添加了不少關於 Yii2 源碼的注釋,之後還會繼續添加~
有興趣的同學也可以參與進來,提交 Yii2 源碼的注釋。