File tree Expand file tree Collapse file tree 2 files changed +44
-6
lines changed Expand file tree Collapse file tree 2 files changed +44
-6
lines changed Original file line number Diff line number Diff line change 33namespace hussainalihussain \phpmvclaravelclonecore ;
44
55use hussainalihussain \phpmvclaravelclonecore \database \Database ;
6- use app \models \User ;
76
8- class Application
7+ class Application extends Event
98{
109 /**
1110 * @var Router
@@ -65,6 +64,16 @@ public function __construct(string $root_path, array $config = [])
6564 $ this ->session = new Session ();
6665 $ this ->userClassName = $ config ['userClassName ' ] ?? '' ;
6766 }
67+
68+ public function registerErrorEvent (\Throwable $ t )
69+ {
70+ $ this ->on (Event::EVENT_ERROR_OCCUR , function () use ($ t ) {
71+ $ this ->response ->setCode ($ t ->getCode ());
72+ echo $ this ->view ->renderView ('_error ' , [
73+ 'exception ' => $ t
74+ ]);
75+ });
76+ }
6877
6978 /**
7079 * @return void
@@ -73,14 +82,17 @@ public function run()
7382 {
7483 try
7584 {
85+ $ this ->trigger (EVENT ::EVENT_BEFORE_REQUEST );
7686 echo $ this ->router ->resolve ();
7787 }
7888 catch (\Exception $ e )
7989 {
80- $ this ->response ->setCode ($ e ->getCode ());
81- echo $ this ->view ->renderView ('_error ' , [
82- 'exception ' => $ e
83- ]);
90+ $ this ->registerErrorEvent ($ e );
91+ $ this ->trigger (Event::EVENT_ERROR_OCCUR );
92+ }
93+ finally
94+ {
95+ $ this ->trigger (Event::EVENT_AFTER_REQUEST );
8496 }
8597 }
8698
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace app \core ;
4+
5+ abstract class Event
6+ {
7+ public const EVENT_BEFORE_REQUEST = 'beforeRequest ' ;
8+ public const EVENT_AFTER_REQUEST = 'afterRequest ' ;
9+ public const EVENT_ERROR_OCCUR = 'errorOccur ' ;
10+ protected $ eventListeners = [];
11+
12+ public function on (string $ eventName , $ callback )
13+ {
14+ $ this ->eventListeners [$ eventName ][] = $ callback ;
15+ }
16+
17+ public function trigger (string $ eventName )
18+ {
19+ $ callbacks = $ this ->eventListeners [$ eventName ] ?? [];
20+
21+ foreach ($ callbacks as $ callback )
22+ {
23+ call_user_func ($ callback );
24+ }
25+ }
26+ }
You can’t perform that action at this time.
0 commit comments