From c9cd1b002dc7e9dda002a589b51822faae2af30b Mon Sep 17 00:00:00 2001 From: hussainaliweb <79245466+hussainaliweb@users.noreply.github.com> Date: Fri, 8 Apr 2022 05:46:11 +0500 Subject: [PATCH] Event.php is added, Also used in Application.php --- Application.php | 24 ++++++++++++++++++------ Event.php | 26 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) create mode 100644 Event.php diff --git a/Application.php b/Application.php index 8b2a3c7..d686cea 100644 --- a/Application.php +++ b/Application.php @@ -3,9 +3,8 @@ namespace hussainalihussain\phpmvclaravelclonecore; use hussainalihussain\phpmvclaravelclonecore\database\Database; -use app\models\User; -class Application +class Application extends Event { /** * @var Router @@ -65,6 +64,16 @@ public function __construct(string $root_path, array $config = []) $this->session = new Session(); $this->userClassName = $config['userClassName'] ?? ''; } + + public function registerErrorEvent(\Throwable $t) + { + $this->on(Event::EVENT_ERROR_OCCUR, function() use ($t) { + $this->response->setCode($t->getCode()); + echo $this->view->renderView('_error', [ + 'exception'=> $t + ]); + }); + } /** * @return void @@ -73,14 +82,17 @@ public function run() { try { + $this->trigger(EVENT::EVENT_BEFORE_REQUEST); echo $this->router->resolve(); } catch (\Exception $e) { - $this->response->setCode($e->getCode()); - echo $this->view->renderView('_error', [ - 'exception'=> $e - ]); + $this->registerErrorEvent($e); + $this->trigger(Event::EVENT_ERROR_OCCUR); + } + finally + { + $this->trigger(Event::EVENT_AFTER_REQUEST); } } diff --git a/Event.php b/Event.php new file mode 100644 index 0000000..c2c976c --- /dev/null +++ b/Event.php @@ -0,0 +1,26 @@ +eventListeners[$eventName][] = $callback; + } + + public function trigger(string $eventName) + { + $callbacks = $this->eventListeners[$eventName] ?? []; + + foreach ($callbacks as $callback) + { + call_user_func($callback); + } + } +} \ No newline at end of file