更多內容: http://blog.yuhai.win
參考地址:
http://www.digpage.com/event.html
1、 yii\base\Event 封裝了與時間相關的有關數據並提供了一些功能函數作爲輔助
class Event extends Object
{
public $name; // 事件名
public $sender; // 事件發佈者,通常是調用了 trigger() 的對象或類。
public $handled = false; // 是否終止事件的後續處理
public $data; // 事件相關數據
private static $_events = [];
public static function on($class, $name, $handler, $data = null,
$append = true)
{
// ... ...
// 用於綁定事件handler
}
public static function off($class, $name, $handler = null)
{
// ... ...
// 用於取消事件handler綁定
}
public static function hasHandlers($class, $name)
{
// ... ...
// 用於判斷是否有相應的handler與事件對應
}
public static function trigger($class, $name, $event = null)
{
// ... ...
// 用於觸發事件
}
}
2、時間handler
所謂時間handler就是時間處理程序,負責時間觸發後怎麼辦的問題,從本質上來說,一個事件handler就是一段PHP代碼,即一個PHP函數。
3、事件的綁定和解除
a、yii\base\Component:: on() 就是用來綁定的
b、yii\base\Component:: off() 就是用來解除的
$person = new Person;
// 使用PHP全局函數作爲handler來進行綁定
$person->on(Person::EVENT_GREET, 'person_say_hello');
// 使用對象$obj的成員函數say_hello來進行綁定
$person->on(Person::EVENT_GREET, [$obj, 'say_hello']);
// 使用類Greet的靜態成員函數say_hello進行綁定
$person->on(Person::EVENT_GREET, ['app\helper\Greet', 'say_hello']);
// 使用匿名函數
$person->on(Person::EVENT_GREET, function ($event) {
echo 'Hello';
});