yii2源码学习笔记(五)

Posted dragon16

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了yii2源码学习笔记(五)相关的知识,希望对你有一定的参考价值。

Event是所有事件类的基类。它封装了与事件相关的参数。

yii2\base\Event.php

  1 <?php
  2 /**
  3  * @link http://www.yiiframework.com/
  4  * @copyright Copyright (c) 2008 Yii Software LLC
  5  * @license http://www.yiiframework.com/license/
  6  */
  7 
  8 namespace yii\base;
  9 
 10 /**
 11  * Event is the base class for all event classes.
 12  *
 13  * It encapsulates the parameters associated with an event.
 14  * The [[sender]] property describes who raises the event.
 15  * And the [[handled]] property indicates if the event is handled.
 16  * If an event handler sets [[handled]] to be true, the rest of the
 17  * uninvoked handlers will no longer be called to handle the event.
 18  * Event是所有事件类的基类。 它封装了与事件相关的参数。 sender属性指的是谁发起来的事件。 
 19  * handled属性指的是事件的处理方式. 如果一个事件处理程序设置了handled为true,其它未处理的事件处理程序将不会被调用。
 20  * Additionally, when attaching an event handler, extra data may be passed
 21  * and be available via the [[data]] property when the event handler is invoked.
 22  * 当附加事件处理程序时,可能会通过额外的数据 ,当事件处理程序被调用时,可通过[ data]属性提供。
 23  * @author Qiang Xue <[email protected]>
 24  * @since 2.0
 25  */
 26 class Event extends Object
 27 {
 28     /**
 29      * 事件的名字,通过[[Component::trigger()]] 和 [[trigger()]]方法设置,事件处理程序可以使用此属性来检查它的处理事件。
 30      * @var string the event name. This property is set by [[Component::trigger()]] and [[trigger()]].
 31      * Event handlers may use this property to check what event it is handling.
 32      */
 33     public $name;
 34     /**
 35      * 触发事件的对象,如果未设置,则设置为调用"trigger()"方法的对象,如果是在静态环境下触发的类级别的事件,属性为空
 36      * @var object the sender of this event. If not set, this property will be
 37      * set as the object whose "trigger()" method is called.
 38      * This property may also be a `null` when this event is a
 39      * class-level event which is triggered in a static context.
 40      */
 41     public $sender;
 42     /**
 43      * 如果一个事件处理程序设置了handled为true,其它未处理的事件处理程序将不会被执行。
 44      * @var boolean whether the event is handled. Defaults to false.
 45      * When a handler sets this to be true, the event processing will stop and
 46      * ignore the rest of the uninvoked event handlers.
 47      */
 48     public $handled = false;
 49     /**
 50      * 附加一个事件处理程序时通过[[Component::on()]]传入data,且对应当前执行的事件处理程序
 51      * @var mixed the data that is passed to [[Component::on()]] when attaching an event handler.
 52      * Note that this varies according to which event handler is currently executing.
 53      */
 54     public $data;
 55     /**
 56      *存储所有的 event,所有的 event 对象/类都共用这一数据
 57      * @var array 
 58      */
 59     private static $_events = [];
 60 
 61 
 62     /**
 63      * Attaches an event handler to a class-level event.
 64      * 为一个类添加事件
 65      * When a class-level event is triggered, event handlers attached
 66      * to that class and all parent classes will be invoked.
 67      * 当一个类级别事件触发,将调用该类和所有父类的事件处理程序。
 68      * For example, the following code attaches an event handler to `ActiveRecord`‘s
 69      * `afterInsert` event:
 70      *
 71      * ~~~
 72      * Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
 73      *     Yii::trace(get_class($event->sender) . ‘ is inserted.‘);
 74      * });
 75      * ~~~
 76      *
 77      * The handler will be invoked for EVERY successful ActiveRecord insertion.
 78      * 该处理程序是将每一个成功的[[ActiveRecord]]插入调用。
 79      * For more details about how to declare an event handler, please refer to [[Component::on()]].
 80      *
 81      * @param string $class the fully qualified class name to which the event handler needs to attach.
 82      * 定义的类级别的对象或者类名称.
 83      * @param string $name the event name.  事件名
 84      * @param callable $handler the event handler.  事件处理程序
 85      * @param mixed $data the data to be passed to the event handler when the event is triggered.
 86      * When the event handler is invoked, this data can be accessed via [[Event::data]].
 87      * 当事件被触发时,将传递给事件处理程序的数据。当调用事件处理程序时,该数据可以通过[[Event::data]]传递
 88      * @param boolean $append whether to append new event handler to the end of the existing
 89      * handler list. If false, the new handler will be inserted at the beginning of the existing
 90      * handler list.是否将新事件处理程序附加到现有的处理程序列表的结尾。如果false,新的处理程序将被插入到现有的处理程序列表开头
 91      * @see off()
 92      */
 93     public static function on($class, $name, $handler, $data = null, $append = true)
 94     {
 95         // 去掉 class 最左边的反斜杠
 96         $class = ltrim($class, ‘\\‘);
 97         if ($append || empty(self::$_events[$name][$class])) {
 98             //如果 append 为true,附加到$_events中名字为 $name 的数组结尾。如果false,被插入列表开头
 99             self::$_events[$name][$class][] = [$handler, $data];
100         } else {
101             array_unshift(self::$_events[$name][$class], [$handler, $data]);
102         }
103     }
104 
105     /**
106      * Detaches an event handler from a class-level event.
107      * 
108      * This method is the opposite of [[on()]].
109      * [[on()]]的反方法,移除一个类的事件
110      * @param string $class the fully qualified class name from which the event handler needs to be detached.
111      * 定义类级别的对象或者类名称.
112      * @param string $name the event name.  事件名
113      * @param callable $handler the event handler to be removed.    事件处理程序
114      * If it is null, all handlers attached to the named event will be removed. 如果是null,移除所有相关事件
115      * @return boolean whether a handler is found and detached. 一个处理程序是否被发现且分离。
116      * @see on()
117      */
118     public static function off($class, $name, $handler = null)
119     {
120        // 去掉最左边的反斜线
121         $class = ltrim($class, ‘\\‘);
122         if (empty(self::$_events[$name][$class])) {
123             return false; // 该事件不存在,返回false
124         }
125         if ($handler === null) {
126             // 如果 $handler 为空,该类下该所有是这个名字的事件移除,
127             unset(self::$_events[$name][$class]);
128             return true;//移除标记
129         } else {
130             $removed = false;//移除标记
131             foreach (self::$_events[$name][$class] as $i => $event) {
132                 // 如果 $handler 不为空,循环 $_events 找到相应的 $handler,只移除这个 $handler 和 data 组成的数组
133                 if ($event[0] === $handler) {
134                     unset(self::$_events[$name][$class][$i]);
135                     $removed = true;//移除标记
136                 }
137             }
138             if ($removed) {// 移除成功,使数组重新变成一个自然数组
139                 self::$_events[$name][$class] = array_values(self::$_events[$name][$class]);
140             }
141 
142             return $removed;
143         }
144     }
145 
146     /**
147      * Returns a value indicating whether there is any handler attached to the specified class-level event.
148      * Note that this method will also check all parent classes to see if there is any handler attached
149      * to the named event.检测在某个类或者对象是否具有某个事件 同时检测父类
150      * @param string|object $class the object or the fully qualified class name specifying the class-level event.
151      * 定义类级别的对象或者类名称.
152      * @param string $name the event name.  事件名
153      * @return boolean whether there is any handler attached to the event. 是否有处理程序连接到事件
154      */
155     public static function hasHandlers($class, $name)
156     {
157         if (empty(self::$_events[$name])) {
158             return false; //如果不存在事件,返回false
159         }
160         if (is_object($class)) {
161             //如果是对象,获取类名
162             $class = get_class($class);
163         } else {
164             //如果是类名,去掉左边的反斜杠
165             $class = ltrim($class, ‘\\‘);
166         }
167         do {// 如果类中找不到,就去父类中找,直到找到或者没有父类了为止,返回true
168             if (!empty(self::$_events[$name][$class])) {
169                 return true;
170             }
171         } while (($class = get_parent_class($class)) !== false);
172 
173         return false;
174     }
175 
176     /**
177      * Triggers a class-level event.    触发类级别事件。
178      * This method will cause invocation of event handlers that are attached to the named event
179      * for the specified class and all its parent classes.该方法将调用指定类中的事件处理程序
180      * @param string|object $class the object or the fully qualified class name specifying the class-level event.
181      * 定义的类级别的对象或者类名称.
182      * @param string $name the event name.  事件名
183      * @param Event $event the event parameter. If not set, a default [[Event]] object will be created.
184      * 事件参数,未设置则默认创建
185      */
186     public static function trigger($class, $name, $event = null)
187     {
188         if (empty(self::$_events[$name])) {
189             return;//如果事件为空,直接返回
190         }
191         if ($event === null) {
192              // 事件不存在,就创建一个静态 Event 对象
193             $event = new static;
194         }
195         $event->handled = false;//事件是否被处理标志,默认未处理
196         $event->name = $name;//事件名
197 
198         if (is_object($class)) {
199             if ($event->sender === null) {
200                 // 如果 $class 是个对象,并且sender为空,就将 $class赋给sender,即$class发起事件
201                 $event->sender = $class;
202             }
203             $class = get_class($class);//获取类名
204         } else {
205             $class = ltrim($class, ‘\\‘);//不是对象,去掉左边的反斜线
206         }
207         do {// 循环类的 $_event,直到遇到 $event->handled 为真或者没有父类了为止
208             if (!empty(self::$_events[$name][$class])) {//找到符合条件的类
209                 foreach (self::$_events[$name][$class] as $handler) {
210                      // 将参数赋到 event 对象的 data 属性上
211                     $event->data = $handler[1];
212                     // 调用 $handler 方法
213                     call_user_func($handler[0], $event);
214                     if ($event->handled) {
215                        // 事件处理程序handled为true,其它未处理的事件处理程序将不会被调用。
216                         return;
217                     }
218                 }
219             }
220         } while (($class = get_parent_class($class)) !== false);
221     }
222 }

 

以上是关于yii2源码学习笔记(五)的主要内容,如果未能解决你的问题,请参考以下文章

yii2源码学习笔记(三)

yii2源码学习笔记(十九)

yii2源码学习笔记(十六)

yii2源码学习笔记(四)

yii2源码学习笔记(六)

yii2源码学习笔记(七)