Events simple event manager: Events
EventsSimple event manager. The Leaps/Events event provides great flexibility for the creation of loosely coupled applications. it allows the extension package to participate in the core execution process of the application without modifying the program code.
Install
"require" : { "php" : ">=5.4.0", "leaps/events": "1.0.*"}
Basic usage
This component is easy to use:
listen('foo',function(){ return 'hello';});$response = $d->trigger('foo');echo $response;
Trigger Event
Just tell the name of the event you want to triggerDispatcherClass can trigger an event:
Trigger an event:
trigger('loaded');
Note that we willTriggerThe execution result of the method is assigned a variable. This method returns an array containing the returned data after all the listeners listening for this event are executed.
If you only want to obtain the first returned data, you can:
Trigger an event and obtain the first returned value:
trigger('loaded');
Note: FirstMethod will trigger all listeners listening for an event, but only the first data is returned.
Trigger an event until an event listener returns non-null data:
first('loaded');
Note: UntilThe method will execute all listeners listening to an event in order before obtaining the first non-null returned data.
Listen to events
No one listens to the event alone. The following shows how to register an event processor for an event:
Register an event processor:
listen('loaded'function() { // I'm executed on the "loaded" event! });
The closure function passing this method will be executed each time the "loaded" event is triggered.
Event Queue
Sometimes you want to store the events to be triggered in the "queue" instead of trigger immediately. This requires the queue and flush methods. First, register an event with a unique identifier in the event queue:
Register an event with the event queue:
queue('loaded', $user->id, array($user));
This method accepts three parameters. The first parameter is the name of the event queue, the second parameter is the unique identifier of the event, and the third parameter is the array passed to the event cleaner, which carries useful data.
Next, we register an event processor for the foo event:
Register an event processor:
flusher('loaded', function($key, $user) { // });
Note that the flusher method accepts two parameters. The first is the unique identifier of an event stored in the event queue. in the preceding example, the user ID is used. The second parameter (more parameters can be added later) is the data carried by this event.
Finally, we call the flush method to handle all events in the queue by the event processor:
flush('foo', function($key, $user) { // });
Project homepage:Http://www.open-open.com/lib/view/home/1430106120693