This tutorial explores the various features of Zend\EventManager.
Typically, an event will be modeled as an object, containing metadata surrounding when and how it was triggered, including the event name, what object triggered the event (the “target”), and what parameters were provided. Events are named, which allows a single listener to branch logic based on the event.
The minimal things necessary to start using events are:
The simplest example looks something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | use Zend\EventManager\EventManager;
$events = new EventManager();
$events->attach('do', function ($e) {
$event = $e->getName();
$params = $e->getParams();
printf(
'Handled event "%s", with parameters %s',
$event,
json_encode($params)
);
});
$params = array('foo' => 'bar', 'baz' => 'bat');
$events->trigger('do', null, $params);
|
The above will result in the following:
Handled event "do", with parameters {"foo":"bar","baz":"bat"}
Note
Throughout this tutorial, we use closures as listeners. However, any valid PHP callback can be attached as a listeners: PHP function names, static class methods, object instance methods, functors, or closures. We use closures within this post simply for illustration and simplicity.
If you were paying attention to the example, you will have noted the null argument. Why is it there?
Typically, you will compose an EventManager within a class, to allow triggering actions within methods. The middle argument to trigger() is the “target”, and in the case described, would be the current object instance. This gives event listeners access to the calling object, which can often be useful.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
class Example implements EventManagerAwareInterface
{
protected $events;
public function setEventManager(EventManagerInterface $events)
{
$events->setIdentifiers(array(
__CLASS__,
get_class($this)
));
$this->events = $events;
}
public function getEventManager()
{
if (!$this->events) {
$this->setEventManager(new EventManager());
}
return $this->events;
}
public function do($foo, $baz)
{
$params = compact('foo', 'baz');
$this->getEventManager()->trigger(__FUNCTION__, $this, $params);
}
}
$example = new Example();
$example->getEventManager()->attach('do', function($e) {
$event = $e->getName();
$target = get_class($e->getTarget()); // "Example"
$params = $e->getParams();
printf(
'Handled event "%s" on target "%s", with parameters %s',
$event,
$target,
json_encode($params)
);
});
$example->do('bar', 'bat');
|
The above is basically the same as the first example. The main difference is that we’re now using that middle argument in order to pass the target, the instance of Example, on to the listeners. Our listener is now retrieving that ($e->getTarget()), and doing something with it.
If you’re reading this critically, you should have a new question: What is the call to setIdentifiers() for?
So far, with both a normal EventManager instance and with the SharedEventManager instance, we’ve seen the usage of singular strings representing the event and target names to which we want to attach. What if you want to attach a listener to multiple events or targets?
The answer is to supply an array of events or targets, or a wildcard, *.
Consider the following examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | // Multiple named events:
$events->attach(
array('foo', 'bar', 'baz'), // events
$listener
);
// All events via wildcard:
$events->attach(
'*', // all events
$listener
);
// Multiple named targets:
$sharedEvents->attach(
array('Foo', 'Bar', 'Baz'), // targets
'doSomething', // named event
$listener
);
// All targets via wildcard
$sharedEvents->attach(
'*', // all targets
'doSomething', // named event
$listener
);
// Mix and match: multiple named events on multiple named targets:
$sharedEvents->attach(
array('Foo', 'Bar', 'Baz'), // targets
array('foo', 'bar', 'baz'), // events
$listener
);
// Mix and match: all events on multiple named targets:
$sharedEvents->attach(
array('Foo', 'Bar', 'Baz'), // targets
'*', // events
$listener
);
// Mix and match: multiple named events on all targets:
$sharedEvents->attach(
'*', // targets
array('foo', 'bar', 'baz'), // events
$listener
);
// Mix and match: all events on all targets:
$sharedEvents->attach(
'*', // targets
'*', // events
$listener
);
|
The ability to specify multiple targets and/or events when attaching can slim down your code immensely.
Another approach to listening to multiple events is via a concept of listener aggregates, represented by Zend\EventManager\ListenerAggregateInterface. Via this approach, a single class can listen to multiple events, attaching one or more instance methods as listeners.
This interface defines two methods, attach(EventManagerInterface $events) and detach(EventManagerInterface $events). Basically, you pass an EventManager instance to one and/or the other, and then it’s up to the implementing class to determine what to do.
As an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | use Zend\EventManager\EventInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\Log\Logger;
class LogEvents implements ListenerAggregateInterface
{
protected $listeners = array();
protected $log;
public function __construct(Logger $log)
{
$this->log = $log;
}
public function attach(EventManagerInterface $events)
{
$this->listeners[] = $events->attach('do', array($this, 'log'));
$this->listeners[] = $events->attach('doSomethingElse', array($this, 'log'));
}
public function detach(EventCollection $events)
{
foreach ($this->listeners as $index => $listener) {
if ($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)));
}
}
|
You can attach this using either attach() or attachAggregate():
$logListener = new LogEvents($logger);
$events->attachAggregate($logListener); // OR
$events->attach($logListener);
Any events the aggregate attaches to will then be notified when triggered.
Why bother? For a couple of reasons:
Sometimes you’ll want to know what your listeners returned. One thing to remember is that you may have multiple listeners on the same event; the interface for results must be consistent regardless of the number of listeners.
The EventManager implementation by default returns a Zend\EventManager\ResponseCollection instance. This class extends PHP’s SplStack, allowing you to loop through responses in reverse order (since the last one executed is likely the one you’re most interested in). It also implements the following methods:
Typically, you should not worry about the return values from events, as the object triggering the event shouldn’t really have much insight into what listeners are attached. However, sometimes you may want to short-circuit execution if interesting results are obtained.
You may want to short-ciruit execution if a particular result is obtained, or if a listener determines that something is wrong, or that it can return something quicker than the target.
As examples, one rationale for adding an EventManager is as a caching mechanism. You can trigger one event early in the method, returning if a cache is found, and trigger another event late in the method, seeding the cache.
The EventManager component offers two ways to handle this. The first is to pass a callback as the last argument to trigger(); if that callback returns a boolean true, execution is halted.
Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public function someExpensiveCall($criteria1, $criteria2)
{
$params = compact('criteria1', 'criteria2');
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
$params,
function ($r) {
return ($r instanceof SomeResultClass);
}
);
if ($results->stopped()) {
return $results->last();
}
// ... do some work ...
}
|
With this paradigm, we know that the likely reason of execution halting is due to the last result meeting the test callback criteria; as such, we simply return that last result.
The other way to halt execution is within a listener, acting on the Event object it receives. In this case, the listener calls stopPropagation(true), and the EventManager will then return without notifying any additional listeners.
1 2 3 4 | $events->attach('do', function ($e) {
$e->stopPropagation();
return new SomeResultClass();
});
|
This, of course, raises some ambiguity when using the trigger paradigm, as you can no longer be certain that the last result meets the criteria it’s searching on. As such, we recommend that you standardize on one approach or the other.
On occasion, you may be concerned about the order in which listeners execute. As an example, you may want to do any logging early, to ensure that if short-circuiting occurs, you’ve logged; or if implementing a cache, you may want to return early if a cache hit is found, and execute late when saving to a cache.
Each of EventManager::attach() and SharedEentManager::attach() accept one additional argument, a priority. By default, if this is omitted, listeners get a priority of 1, and are executed in the order in which they are attached. However, if you provide a priority value, you can influence order of execution.
To borrow an example from earlier:
1 2 3 4 5 6 7 8 9 10 11 12 | $priority = 100;
$events->attach('Example', 'do', function($e) {
$event = $e->getName();
$target = get_class($e->getTarget()); // "Example"
$params = $e->getParams();
printf(
'Handled event "%s" on target "%s", with parameters %s',
$event,
$target,
json_encode($params)
);
}, $priority);
|
This would execute with high priority, meaning it would execute early. If we changed $priority to -100, it would execute with low priority, executing late.
While you can’t necessarily know all the listeners attached, chances are you can make adequate guesses when necessary in order to set appropriate priority values. We advise avoiding setting a priority value unless absolutely necessary.
Hopefully some of you have been wondering, “where and when is the Event object created”? In all of the examples above, it’s created based on the arguments passed to trigger() – the event name, target, and parameters. Sometimes, however, you may want greater control over the object.
As an example, one thing that looks like a code smell is when you have code like this:
1 2 3 4 | $routeMatch = $e->getParam('route-match', false);
if (!$routeMatch) {
// Oh noes! we cannot do our work! whatever shall we do?!?!?!
}
|
The problems with this are several. First, relying on string keys is going to very quickly run into problems – typos when setting or retrieving the argument can lead to hard to debug situations. Second, we now have a documentation issue; how do we document expected arguments? how do we document what we’re shoving into the event? Third, as a side effect, we can’t use IDE or editor hinting support – string keys give these tools nothing to work with.
Similarly, consider how you might represent a computational result of a method when triggering an event. As an example:
1 2 3 4 5 6 7 8 9 | // in the method:
$params['__RESULT'] = $computedResult;
$events->trigger(__FUNCTION__ . '.post', $this, $params);
// in the listener:
$result = $e->getParam('__RESULT__');
if (!$result) {
// Oh noes! we cannot do our work! whatever shall we do?!?!?!
}
|
Sure, that key may be unique, but it suffers from a lot of the same issues.
So, the solution is to create custom events. As an example, we have a custom MvcEvent in the ZF2 MVC layer. This event composes the application instance, the router, the route match object, request and response objects, the view model, and also a result. We end up with code like this in our listeners:
1 2 3 4 5 6 | $response = $e->getResponse();
$result = $e->getResult();
if (is_string($result)) {
$content = $view->render('layout.phtml', array('content' => |