File tree 2 files changed +44
-6
lines changed
2 files changed +44
-6
lines changed Original file line number Diff line number Diff line change 3
3
namespace hussainalihussain \phpmvclaravelclonecore ;
4
4
5
5
use hussainalihussain \phpmvclaravelclonecore \database \Database ;
6
- use app \models \User ;
7
6
8
- class Application
7
+ class Application extends Event
9
8
{
10
9
/**
11
10
* @var Router
@@ -65,6 +64,16 @@ public function __construct(string $root_path, array $config = [])
65
64
$ this ->session = new Session ();
66
65
$ this ->userClassName = $ config ['userClassName ' ] ?? '' ;
67
66
}
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
+ }
68
77
69
78
/**
70
79
* @return void
@@ -73,14 +82,17 @@ public function run()
73
82
{
74
83
try
75
84
{
85
+ $ this ->trigger (EVENT ::EVENT_BEFORE_REQUEST );
76
86
echo $ this ->router ->resolve ();
77
87
}
78
88
catch (\Exception $ e )
79
89
{
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 );
84
96
}
85
97
}
86
98
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