Zendframework Event Management (2), zendframework event
First, you need to clarify several issues:
Q1. What is an event?
A: An event is A behavior with A name. When this action occurs, the event is triggered.
Q2. What is the listener?
A: The Listener determines the logical expression of the event, which is triggered by the event. Listeners and events are usually paired. Of course, an event can correspond to multiple listeners. Listeners are responses to events. When an event is triggered, the listener responds. In this way, multiple events can trigger a listener to respond. An event can also be reflected by multiple listeners. (One sentence: the relationship between listeners and events can be one-to-many or multiple-to-one)
Q3. What does the event manager do?
A: The event manager (EventManager) is used to manage events. But how can he manage it? The event manager usually aggregates multiple listeners for multiple events (the events and listeners here are an indefinite number (either one or multiple ]). The event manager is also responsible for triggering events.
Generally, we use objects to represent events. An event object describes the basic elements of an event, including when and how to trigger the event.
Basic elements of an event: event name, target (the object that triggers the event, usually the event object itself), and event parameters. Previously, we mentioned that an event is equivalent to an action. In a program, we often use methods or functions to represent actions. Therefore, event parameters are also function parameters.
In addition, Shared managers: As mentioned earlier, an event can target multiple listeners. This is implemented through Shared managers. The implementation of EventManager includes (combined) javasdeventmanagerinterface [code injection is used in the constructor or setSharedManager. For details, you can view the source code]), while the javasdeventmanagerinterface describes an object of an aggregate listener, these listeners only connect to events with the specified identifier. Javasdeventmanager does not trigger events. It only provides listeners and connects to events. EventManger queries includeventmangaer to obtain the listener with a specific identifier.
Several important actions in EventManager:
1. Create an event: Creating an event is actually just creating an instance of EventManagerInterface.
2. trigger events: Trigger is generally used to trigger an event in the event action, so that this event can be directly triggered when we execute this behavior. FUNCTION prototype: trigger ($ eventName, $ target = null, $ argv = []); $ eventName is generally a time behavior name (commonly used _ FUNCTION _ instead ), $ target indicates that the event object can be replaced by $ this, and $ argv indicates the parameter of the incoming event (generally the parameter of event behavior ).
Of course, trigger events are not only trigger, but also triggerUntil, triggerEvent, and triggerEventUntil. From the name, we can see that there are two types: trigger and triggerEvent. trigger only triggers events, and you do not need to create an event instance, trigger not only triggers events, but also triggers listeners, and requires event instances. A callback function is required for all methods with the Until suffix. The result of each listener is uploaded to the callback function. If the callback function returns a Boolean value of true, EventManager must short the listener. (For short circuits, see the short circuit below)
For more information, see the official API or EventMangerInterface annotations.
3. Create a listener and connect to the event:
Listeners can be created either through EventManager or through javasdeventmanager. Both use the attach method, but the parameters are a bit different.
Let's first look at the EventManager method:
Method prototype: attach ($ eventName, callable $ listener, $ priority = 1)
Simple: We only need the event name and a callable function. The default priority is 1 (the priority of the built-in events in zend is mostly negative, so if you want to make the custom listener have a higher priority, just assign a positive value .)
The callable function is our listener. The event name has a special case: "*". This is similar to regular expression matching. It connects all events to the listener.
Let's take a look at the deployment deventmanager method:
Method prototype: attach ($ identifier, $ eventName, callable $ listener, $ priority = 1 );
An identifier parameter is added in a different area than the previous one. The source code of identifier is described as follows:
Used to pull shared signals from includeventmanagerinterface instance;
Used to pull the sharing signal from the zoodeventmanager instance. Identifier is an array. According to my understanding, if an event (note that the producer deventmanager cannot create an event) defines identifier, this event can be shared. Let the later javasdeventmanger instance pass in the identifier parameter when using attach to create the listener. EventManager can use the identifier parameter to query all listeners.
It is confusing that with the event name, you can use the event name to query related listeners. Why do you need to add the identifier attribute? I have considered the issue of event inheritance: Suppose there is an event class Foo that contains an event behavior act, SubFoo inherits the Foo class and overrides the event behavior act in it. Both classes have the same event Name act. At this time, if the listener is queried through the event name, there will obviously be conflicts. At this time, we define identifier [_ CLASS __, get_class ($ this)], and specify identifier as SubFoo In the listener, which will obviously match the event behavior act in the SubFoo CLASS.
In the above example, we can monitor multiple events through mongodeventmanager. In addition, we can also use listener aggregates. Use Zend \ EventManager \ listeneraggresponinterface to let a class Listen to multiple events and connect one or more instance methods as listeners. This interface also defines attach (EventManagerInterface $ events) and detach (EventManagerInterface $ events ). In the specific implementation of attach, we use the EventManager instance method attach to listen to multiple events.
use Zend\EventManager\EventInterface;use Zend\EventManager\EventManagerInterface;use Zend\EventManager\ListenerAggregateInterface;use Zend\Log\Logger;class LogEvents implements ListenerAggregateInterface{ private $listeners = []; private $log; public function __construct(Logger $log) { $this->log = $log; } public function attach(EventManagerInterface $events) { $this->listeners[] = $events->attach('do', [$this, 'log']); $this->listeners[] = $events->attach('doSomethingElse', [$this, 'log']); } public function detach(EventCollection $events) { foreach ($this->listeners as $index => $listener) { $events->detach($listener); unset($this->listeners[$index]); } } public function log(EventInterface $e) { $event = $e->getName(); $params = $e->getParams(); $this->log->info(sprintf('%s: %s', $event, json_encode($params))); }}
Advantages of using Aggregate:
1. allow you to use stateful listeners
2. Combine multiple similar listeners in a single class and connect them at one time
Result returned by the inner listener
We have a listener, but how do we receive the returned results? By default, EventManager returns a ResponseCollection instance. This class inherits from PHP's SplStack. The basic structure is a stack, so you can traverse Responses in reverse order.
ResponseCollection provides several useful methods:
First (): Get the first result
Last (): Get the last result
Contains ($ value): Check whether the stack contains a value. If yes, true is returned; otherwise, false is returned.
Short loop listener execution:
What is short loop? Suppose you want to do one thing until it has a result. This is a loop. If you know the results in advance (for example, you have done this before), then you have to finish it completely. At this time, you only need to execute a short loop.
We have a caching mechanism when adding EventManager. Trigger an event in a method. If we find a cache result, it will be returned directly. If no cache result is found, the triggered event is cached for future use. In fact, it is similar to the high-speed cache in computer hardware.
The EventManager component provides two Processing Methods: 1. triggerUntil (); 2. triggerEventUntil. Both methods accept a callback function as the first parameter. If the callback function returns true, the execution stops.
public function someExpensiveCall($criteria1, $criteria2){ $params = compact('criteria1', 'criteria2'); $results = $this->getEventManager()->triggerUntil( function($r){ return ($r instanceof SomeResultClass); }, __FUNCTION__, $this, $params ); if($results->stopped()) { return $results->last()' }}
From the above example, we know that if the execution is stopped, it is likely that the final result in the stack meets our requirements. In this way, we only need to return this result. Why do we need to perform extra calculations?
Processing stops execution in the event. We can also stop execution in the listener. The reason is that we have received an event, and now we have received the same event, so we can use the previous result as a matter of course. In this case, the listener calls stopPropagation (true), and then EventManager returns directly without continuing to notify the additional listener.
$events->attach('do', function($e) { $e->stopPropagation(); return new SomeResultClass();});
Of course, using the trigger example may lead to ambiguity. After all, you do not know whether the final result meets the requirements.
Keeping it in order.
Occasionally, you will be concerned about the execution sequence of the listener. We control the execution sequence by the listener priority (the short loop mentioned above also affects the execution sequence ). Each EventManager: attach () and includeventmanager: attach () will accept an out-of-the-box parameter: priority. The default value is 1. We can omit this parameter. If you provide this parameter: the execution of the parameter with a higher priority is earlier, the execution of the parameter with a lower priority may be postponed.
Custom Event object:
We previously used trigger () to trigger an event. At this time, we also created an event. However, the trigger () parameter is limited. We can only specify the event object, parameter, and name. In fact, we can create a custom event, which is an important event in Zendframework: MvcEvent. Obviously, MvcEvent is a custom event that combines application instances, routers, route matching objects, request and response objects, view models, and results. We can check the MvcEvent source code and find that the MvcEvent class actually inherits the Event class. Similarly, our custom Event objects can inherit the Event class or MvcEvent.
$event = new CustomEvent();$event->setName('foo');$event->setTarget($this);$event->setSomeKey($value);//injected with event name and target:$events->triggerEvent($event);//Use triggerEventUntil() for criteria-based short-circuiting:$results = $events->triggerEventUntil($callback, $event);
The code above shows that an event object is created using the Custom Event class, and the relevant interceptor is called to set properties for the event object. Do we still use trigger () to trigger an event with an event object? Obviously not. We use the triggerEvent ($ event) method, which receives an event object. TriggerEventUntil has a callback function, which serves as the basis for short loop.