Documentation

The EventManager - Zend_EventManager

The EventManager

Overview

Zend_EventManager is a component designed for the following use cases:

  • Implementing simple subject/observer patterns.

  • Implementing Aspect-Oriented designs.

  • Implementing event-driven architectures.

The basic architecture allows you to attach and detach listeners to named events, both on a per-instance basis as well as statically; trigger events; and interrupt execution of listeners.

Quick Start

Typically, you will compose a Zend_EventManager_EventManager instance in a class.

  1. class Foo
  2. {
  3.     protected $events;
  4.  
  5.     public function events(Zend_EventManager_EventCollection $events = null)
  6.     {
  7.         if (null !== $events) {
  8.             $this->events = $events;
  9.         } elseif (null === $this->events) {
  10.             $this->events = new Zend_EventManager_EventManager(__CLASS__);
  11.         }
  12.         return $this->events;
  13.     }
  14. }

The above allows users to access the EventManager instance, or reset it with a new instance; if one does not exist, it will be lazily instantiated on-demand.

An EventManager is really only interesting if it triggers some events. Basic triggering takes three arguments: the event name, which is usually the current function/method name; the "context", which is usually the current object instance; and the arguments, which are usually the arguments provided to the current function/method.

  1. class Foo
  2. {
  3.     // ... assume events definition from above
  4.  
  5.     public function bar($baz, $bat = null)
  6.     {
  7.         $params = compact('baz', 'bat');
  8.         $this->events()->trigger(__FUNCTION__, $this, $params);
  9.     }
  10. }

In turn, triggering events is only interesting if something is listening for the event. Listeners attach to the EventManager, specifying a named event and the callback to notify. The callback receives a Zend_EventManager_Event object, which has accessors for retrieving the event name, context, and parameters. Let's add a listener, and trigger the event.

  1. $log = Zend_Log::factory($someConfig);
  2. $foo = new Foo();
  3. $foo->events()->attach('bar', function ($e) use ($log) {
  4.     $event  = $e->getName();
  5.     $target = get_class($e->getTarget());
  6.     $params = json_encode($e->getParams());
  7.  
  8.     $log->info(sprintf(
  9.         '%s called on %s, using params %s',
  10.         $event,
  11.         $target,
  12.         $params
  13.     ));
  14. });
  15.  
  16. // Results in log message:
  17. $foo->bar('baz', 'bat');
  18. // reading: bar called on Foo, using params {"baz" : "baz", "bat" : "bat"}"

Note that the second argument to attach() is any valid callback; an anonymous function is shown in the example in order to keep the example self-contained. However, you could also utilize a valid function name, a functor, a string referencing a static method, or an array callback with a named static method or instance method. Again, any PHP callback is valid.

Sometimes you may want to specify listeners without yet having an object instance of the class composing an EventManager. The Zend_EventManager_StaticEventManager allows you to do this. The call to attach is identical to the EventManager, but expects an additional parameter at the beginning: a named instance. Remember the example of composing an EventManager, how we passed it __CLASS__? That value, or any strings you provide in an array to the constructor, may be used to identify an instance when using the StaticEventManager. As an example, we could change the above example to attach statically:

  1. $log = Zend_Log::factory($someConfig);
  2. $events = Zend_EventManager_StaticEventManager::getInstance();
  3. $events->attach('Foo', 'bar', function ($e) use ($log) {
  4.     $event  = $e->getName();
  5.     $target = get_class($e->getTarget());
  6.     $params = json_encode($e->getParams());
  7.  
  8.     $log->info(sprintf(
  9.         '%s called on %s, using params %s',
  10.         $event,
  11.         $target,
  12.         $params
  13.     ));
  14. });
  15.  
  16. // Later, instantiate Foo:
  17. $foo = new Foo();
  18.  
  19. // And we can still trigger the above event:
  20. $foo->bar('baz', 'bat');
  21. // results in log message:
  22. // bar called on Foo, using params {"baz" : "baz", "bat" : "bat"}"

The EventManager also provides the ability to detach listeners, short-circuit execution of an event either from within a listener or by testing return values of listeners, test and loop through the results returned by listeners, prioritize listeners, and more. Many of these features are detailed in the examples.

Wildcard Listeners

Sometimes you'll want to attach the same listener to many events or to all events of a given instance -- or potentially, with the static manager, many contexts, and many events. The EventManager component allows for this.

Example #1 Attaching to many events at once

  1. $events = new Zend_EventManager_EventManager();
  2. $events->attach(array('these', 'are', 'event', 'names'), $callback);

Note that if you specify a priority, that priority will be used for all events specified.

Example #2 Attaching using the wildcard

  1. $events = new Zend_EventManager_EventManager();
  2. $events->attach('*', $callback);

Note that if you specify a priority, that priority will be used for this listener for any event triggered.

What the above specifies is that any event triggered will result in notification of this particular listener.

Example #3 Attaching to many events at once via the StaticEventManager

  1. $events = Zend_EventManager_StaticEventManager::getInstance();
  2. // Attach to many events on the context "foo"
  3. $events->attach('foo', array('these', 'are', 'event', 'names'), $callback);
  4.  
  5. // Attach to many events on the contexts "foo" and "bar"
  6. $events->attach(array('foo', 'bar'), array('these', 'are', 'event', 'names'), $callback);

Note that if you specify a priority, that priority will be used for all events specified.

Example #4 Attaching to many events at once via the StaticEventManager

  1. $events = Zend_EventManager_StaticEventManager::getInstance();
  2. // Attach to all events on the context "foo"
  3. $events->attach('foo', '*', $callback);
  4.  
  5. // Attach to all events on the contexts "foo" and "bar"
  6. $events->attach(array('foo', 'bar'), '*', $callback);

Note that if you specify a priority, that priority will be used for all events specified.

The above is specifying that for the contexts "foo" and "bar", the specified listener should be notified for any event they trigger.

Configuration Options

Zend_EventManager_EventManager Options

identifier

A string or array of strings to which the given EventManager instance can answer when accessed via the StaticEventManager.

event_class

The name of an alternate Zend_EventManager_Event class to use for representing events passed to listeners.

static_connections

An instance of a Zend_EventManager_StaticEventCollection instance to use when triggering events. By default, this will use the global Zend_EventManager_StaticEventManager instance, but that can be overridden by passing a value to this method. A null value will prevent the instance from triggering any further statically attached listeners.

Available Methods

__construct
__construct ( null|string|int $identifier )

Constructs a new EventManager instance, using the given identifier, if provided, for purposes of static attachment.

setEventClass
setEventClass ( string $class )

Provide the name of an alternate Zend_EventManager_Event class to use when creating events to pass to triggered listeners.

setStaticConnections
setStaticConnections ( Zend_EventManager_StaticEventCollection $connections = null )

An instance of a Zend_EventManager_StaticEventCollection instance to use when triggering events. By default, this will use the global Zend_EventManager_StaticEventManager instance, but that can be overridden by passing a value to this method. A null value will prevent the instance from triggering any further statically attached listeners.

getStaticConnections
getStaticConnections ( void

Returns the currently attached Zend_EventManager_StaticEventCollection instance, lazily retrieving the global Zend_EventManager_StaticEventManager instance if none is attached and usage of static listeners hasn't been disabled by passing a null value to setStaticConnections(). Returns either a boolean false if static listeners are disabled, or a StaticEventCollection instance otherwise.

trigger
trigger ( string $event, mixed $target, mixed $argv, callback $callback )

Triggers all listeners to a named event. The recommendation is to use the current function/method name for $event, appending it with values such as ".pre", ".post", etc. as needed. $context should be the current object instance, or the name of the function if not triggering within an object. $params should typically be an associative array or ArrayAccess instance; we recommend using the parameters passed to the function/method (compact() is often useful here). This method can also take a callback and behave in the same way as triggerUntil().

The method returns an instance of Zend_EventManager_ResponseCollection, which may be used to introspect return values of the various listeners, test for short-circuiting, and more.

triggerUntil
triggerUntil ( string $event, mixed $context, mixed $argv, callback $callback )

Triggers all listeners to a named event, just like trigger(), with the addition that it passes the return value from each listener to $callback; if $callback returns a boolean true value, execution of the listeners is interrupted. You can test for this using $result->stopped().

attach
attach ( string $event, callback $callback, int $priority )

Attaches $callback to the Zend_EventManager_EventManager instance, listening for the event $event. If a $priority is provided, the listener will be inserted into the internal listener stack using that priority; higher values execute earliest. (Default priority is "1", and negative priorities are allowed.)

The method returns an instance of Zend_Stdlib_CallbackHandler; this value can later be passed to detach() if desired.

attachAggregate
attachAggregate ( string|Zend_EventManager_ListenerAggregate $aggregate )

If a string is passed for $aggregate, instantiates that class. The $aggregate is then passed the EventManager instance to its attach() method so that it may register listeners.

The ListenerAggregate instance is returned.

detach
detach ( Zend_Stdlib_CallbackHandler $listener )

Scans all listeners, and detaches any that match $listener so that they will no longer be triggered.

Returns a boolean true if any listeners have been identified and unsubscribed, and a boolean false otherwise.

detachAggregate
detachAggregate ( Zend_EventManager_ListenerAggregate $aggregate )

Loops through all listeners of all events to identify listeners that are represented by the aggregate; for all matches, the listeners will be removed.

Returns a boolean true if any listeners have been identified and unsubscribed, and a boolean false otherwise.

detachAggregate
getEvents ( void

Returns an array of all event names that have listeners attached.

getListeners
getListeners ( string $event )

Returns a Zend_Stdlib_PriorityQueue instance of all listeners attached to $event.

clearListeners
clearListeners ( string $event )

Removes all listeners attached to $event.

prepareArgs
prepareArgs ( array $args )

Creates an ArrayObject from the provided $args. This can be useful if you want yours listeners to be able to modify arguments such that later listeners or the triggering method can see the changes.

Examples

Example #5 Modifying Arguments

Occasionally it can be useful to allow listeners to modify the arguments they receive so that later listeners or the calling method will receive those changed values.

As an example, you might want to pre-filter a date that you know will arrive as a string and convert it to a DateTime argument.

To do this, you can pass your arguments to prepareArgs(), and pass this new object when triggering an event. You will then pull that value back into your method.

  1. class ValueObject
  2. {
  3.     // assume a composed event manager
  4.  
  5.     function inject(array $values)
  6.     {
  7.         $argv = compact('values');
  8.         $argv = $this->events()->prepareArgs($argv);
  9.         $this->events()->trigger(__FUNCTION__, $this, $argv);
  10.         $date = isset($argv['values']['date']) ? $argv['values']['date'] : new DateTime('now');
  11.  
  12.         // ...
  13.     }
  14. }
  15.  
  16. $v = new ValueObject();
  17.  
  18. $v->events()->attach('inject', function($e) {
  19.     $values = $e->getParam('values');
  20.     if (!$values) {
  21.         return;
  22.     }
  23.     if (!isset($values['date'])) {
  24.         $values['date'] = new DateTime('now');
  25.         return;
  26.     }
  27.     $values['date'] = new Datetime($values['date']);
  28. });
  29.  
  30. $v->inject(array(
  31.     'date' => '2011-08-10 15:30:29',
  32. ));

Example #6 Short Circuiting

One common use case for events is to trigger listeners until either one indicates no further processing should be done, or until a return value meets specific criteria. As examples, if an event creates a Response object, it may want execution to stop.

  1. $listener = function($e) {
  2.     // do some work
  3.    
  4.     // Stop propagation and return a response
  5.     $e->stopPropagation(true);
  6.     return $response;
  7. };

Alternately, we could do the check from the method triggering the event.

  1. class Foo implements Dispatchable
  2. {
  3.     // assume composed event manager
  4.  
  5.     public function dispatch(Request $request, Response $response = null)
  6.     {
  7.         $argv = compact('request', 'response');
  8.         $results = $this->events()->triggerUntil(__FUNCTION__, $this, $argv, function($v) {
  9.             return ($v instanceof Response);
  10.         });
  11.     }
  12. }

Typically, you may want to return a value that stopped execution, or use it some way. Both trigger() and triggerUntil() return a Zend_EventManager_ResponseCollection instance; call its stopped() method to test if execution was stopped, and last() method to retrieve the return value from the last executed listener:

  1. class Foo implements Dispatchable
  2. {
  3.     // assume composed event manager
  4.  
  5.     public function dispatch(Request $request, Response $response = null)
  6.     {
  7.         $argv = compact('request', 'response');
  8.         $results = $this->events()->triggerUntil(__FUNCTION__, $this, $argv, function($v) {
  9.             return ($v instanceof Response);
  10.         });
  11.  
  12.         // Test if execution was halted, and return last result:
  13.         if ($results->stopped()) {
  14.             return $results->last();
  15.         }
  16.  
  17.         // continue...
  18.     }
  19. }

Example #7 Assigning Priority to Listeners

One use case for the EventManager is for implementing caching systems. As such, you often want to check the cache early, and save to it late.

The third argument to attach() is a priority value. The higher this number, the earlier that listener will execute; the lower it is, the later it executes. The value defaults to 1, and values will trigger in the order registered within a given priority.

So, to implement a caching system, our method will need to trigger an event at method start as well as at method end. At method start, we want an event that will trigger early; at method end, an event should trigger late.

Here is the class in which we want caching:

  1. class SomeValueObject
  2. {
  3.     // assume it composes an event manager
  4.  
  5.     public function get($id)
  6.     {
  7.         $params = compact('id');
  8.         $results = $this->events()->trigger('get.pre', $this, $params);
  9.  
  10.         // If an event stopped propagation, return the value
  11.         if ($results->stopped()) {
  12.             return $results->last();
  13.         }
  14.  
  15.         // do some work...
  16.  
  17.         $params['__RESULT__'] = $someComputedContent;
  18.         $this->events()->trigger('get.post', $this, $params);
  19.     }
  20. }

Now, let's create a ListenerAggregate that can handle caching for us:

  1. class CacheListener implements Zend_EventManager_ListenerAggregate
  2. {
  3.     protected $cache;
  4.  
  5.     public function __construct(Cache $cache)
  6.     {
  7.         $this->cache = $cache;
  8.     }
  9.  
  10.     public function attach(Zend_EventManager_EventCollection $events)
  11.     {
  12.         $events->attach('get.pre', array($this, 'load'), 100);
  13.         $events->attach('get.post', array($this, 'save'), -100);
  14.     }
  15.  
  16.     public function load($e)
  17.     {
  18.         $id = get_class($e->getTarget()) . '-' . json_encode($e->getParams());
  19.         if (false !== ($content = $this->cache->load($id))) {
  20.             $e->stopPropagation(true);
  21.             return $content;
  22.         }
  23.     }
  24.  
  25.     public function save($e)
  26.     {
  27.         $params  = $e->getParams();
  28.         $content = $params['__RESULT__'];
  29.         unset($params['__RESULT__']);
  30.  
  31.         $id = get_class($e->getTarget()) . '-' . json_encode($params);
  32.         $this->cache->save($content, $id);
  33.     }
  34. }

We can then attach the aggregate to an instance.

  1. $value         = new SomeValueObject();
  2. $cacheListener = new CacheListener($cache);
  3. $value->events()->attachAggregate($cacheListener);

Now, as we call get(), if we have a cached entry, it will be returned immediately; if not, a computed entry will be cached when we complete the method.

Copyright

© 2006-2021 by Zend by Perforce. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.

Contacts