2
2
3
3
4
4
use Inhere \Event \Event ;
5
- use Inhere \Event \EventAwareTrait ;
5
+ use Inhere \Event \EventManagerAwareTrait ;
6
6
use Inhere \Event \EventInterface ;
7
7
use Inhere \Event \EventManager ;
8
8
use Inhere \Event \Examples \ExamHandler ;
12
12
function exam_handler (EventInterface $ event )
13
13
{
14
14
$ pos = __METHOD__ ;
15
- echo "handle the event {$ event ->getName ()} on the: $ pos \n" ;
15
+ echo "handle the event ' {$ event ->getName ()}' on the: $ pos \n" ;
16
16
}
17
17
18
18
class ExamListener1
@@ -21,60 +21,65 @@ public function messageSent(EventInterface $event)
21
21
{
22
22
$ pos = __METHOD__ ;
23
23
24
- echo "handle the event {$ event ->getName ()} on the: $ pos \n" ;
24
+ echo "handle the event ' {$ event ->getName ()}' on the: $ pos \n" ;
25
25
}
26
26
}
27
27
28
28
class ExamListener2
29
29
{
30
30
public function __invoke (EventInterface $ event )
31
31
{
32
+ // $event->stopPropagation(true);
32
33
$ pos = __METHOD__ ;
33
- echo "handle the event {$ event ->getName ()} on the: $ pos \n" ;
34
+ echo "handle the event ' {$ event ->getName ()}' on the: $ pos \n" ;
34
35
}
35
36
}
36
37
37
38
// create event class
38
39
class MessageEvent extends Event
39
40
{
40
- protected $ name = 'messageSent ' ;
41
-
42
41
// append property ...
43
42
public $ message = 'oo a text ' ;
44
43
}
45
44
46
45
class Mailer
47
46
{
48
- use EventAwareTrait ;
47
+ use EventManagerAwareTrait ;
49
48
50
49
const EVENT_MESSAGE_SENT = 'messageSent ' ;
51
50
52
51
public function send ($ message )
53
52
{
54
53
// ...发送 $message 的逻辑...
55
54
56
- $ event = new MessageEvent ;
55
+ $ event = new MessageEvent ( self :: EVENT_MESSAGE_SENT ) ;
57
56
$ event ->message = $ message ;
58
57
59
58
// trigger event
60
- $ this ->eventManager ->trigger (self :: EVENT_MESSAGE_SENT , $ event );
59
+ $ this ->eventManager ->trigger ($ event );
61
60
62
61
// var_dump($event);
63
62
}
64
63
}
65
64
66
65
$ em = new EventManager ();
66
+
67
67
$ em ->attach (Mailer::EVENT_MESSAGE_SENT , 'exam_handler ' );
68
68
$ em ->attach (Mailer::EVENT_MESSAGE_SENT , function (EventInterface $ event )
69
69
{
70
70
$ pos = __METHOD__ ;
71
- echo "handle the event {$ event ->getName ()} on the: $ pos \n" ;
71
+ echo "handle the event ' {$ event ->getName ()}' on the: $ pos \n" ;
72
72
});
73
- $ em ->attach (Mailer::EVENT_MESSAGE_SENT , new ExamListener1 ());
73
+ $ em ->attach (Mailer::EVENT_MESSAGE_SENT , new ExamListener1 (), 10 );
74
74
$ em ->attach (Mailer::EVENT_MESSAGE_SENT , new ExamListener2 ());
75
75
$ em ->attach (Mailer::EVENT_MESSAGE_SENT , new ExamHandler ());
76
76
77
+ $ em ->attach ('* ' , function (EventInterface $ event )
78
+ {
79
+ echo "handle the event ' {$ event ->getName ()}' on the global listener. \n" ;
80
+ });
81
+
77
82
$ mailer = new Mailer ();
78
83
$ mailer ->setEventManager ($ em );
79
84
80
- $ mailer ->send ('hello, world! ' );
85
+ $ mailer ->send ('hello, world! ' );
0 commit comments