File tree Expand file tree Collapse file tree 1 file changed +79
-0
lines changed Expand file tree Collapse file tree 1 file changed +79
-0
lines changed Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ interface Subject
4
+ {
5
+ public function attach ($ observable );
6
+
7
+ public function detach ($ observer );
8
+
9
+ public function notify ();
10
+ }
11
+
12
+ interface Observer
13
+ {
14
+ public function handle ();
15
+ }
16
+
17
+ class Login implements Subject
18
+ {
19
+ protected $ observers = [];
20
+
21
+ public function attach ($ observable )
22
+ {
23
+ if (is_array ($ observable )) {
24
+ foreach ($ observable as $ observer ) {
25
+ if (!$ observer instanceof Observer)
26
+ throw new Exception ();
27
+ $ this ->attach ($ observer );
28
+ }
29
+
30
+ return ;
31
+ }
32
+
33
+ $ this ->observers [] = $ observable ;
34
+
35
+ return ;
36
+ }
37
+
38
+ public function detach ($ index )
39
+ {
40
+ unset($ this ->observers [$ index ]);
41
+ }
42
+
43
+ public function notify ()
44
+ {
45
+ foreach ($ this ->observers as $ observer ) {
46
+ $ observer ->handle ();
47
+ }
48
+ }
49
+
50
+ public function fire ()
51
+ {
52
+ $ this ->notify ();
53
+ }
54
+ }
55
+
56
+ class LogHandler implements Observer
57
+ {
58
+ public function handle ()
59
+ {
60
+ echo "Logged in something \n" ;
61
+ }
62
+ }
63
+
64
+ class EmailHandler implements Observer
65
+ {
66
+ public function handle ()
67
+ {
68
+ echo "Fire of an email \n" ;
69
+ }
70
+ }
71
+
72
+ $ login = new Login ();
73
+ $ login ->attach ([
74
+ new LogHandler (),
75
+ new EmailHandler ()
76
+ ]);
77
+
78
+ $ login ->fire ();
79
+
You can’t perform that action at this time.
0 commit comments