From 9ca39406bc3b3b7dd87c325a3aa67076c947e210 Mon Sep 17 00:00:00 2001 From: shirne Date: Wed, 11 Sep 2024 08:00:03 +0800 Subject: [PATCH] improve event --- src/application/common/core/AppLifecycle.php | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/application/common/core/AppLifecycle.php b/src/application/common/core/AppLifecycle.php index 2cce142c..96f1219e 100644 --- a/src/application/common/core/AppLifecycle.php +++ b/src/application/common/core/AppLifecycle.php @@ -7,6 +7,29 @@ class AppLifecycle { + protected static $events = []; + public static function addEvent($event, $callback) + { + if (!isset(self::$events[$event])) { + self::$events[$event] = []; + } + self::$events[$event][] = $callback; + } + + public static function triggerEvent($event, ...$args) + { + if (!empty(self::$events[$event])) { + foreach (self::$events[$event] as $callback) { + try { + if (empty($args)) $args = []; + call_user_func_array($callback, $args); + } catch (\Exception $e) { + Log::warning("Event call error: $event" . var_export($callback) . "\n $e"); + } + } + } + } + public function appInit() { Log::record('app_init'); @@ -24,21 +47,25 @@ public function appInit() public function appBegin() { Log::record('app_begin'); + static::triggerEvent('app_begin'); } public function moduleInit() { Log::record('module_init'); + static::triggerEvent('module_init'); } public function actionBegin() { Log::record('action_begin'); + static::triggerEvent('action_begin'); } public function viewFilter() { Log::record('view_filter'); + static::triggerEvent('view_filter'); } public function logWrite() { @@ -47,5 +74,6 @@ public function logWrite() public function appEnd() { Log::record('app_end'); + static::triggerEvent('app_end'); } }