Zend Framework 2.0 Event Manager (The EventManager) introductory tutorial, zendeventmanager_PHP tutorial

WBOY
Release: 2016-07-13 10:21:00
Original
858 people have browsed it

Zend Framework 2.0 Event Manager (The EventManager) introductory tutorial, zendeventmanager

Overview

EventManger is a component designed for the following use cases:

Copy code The code is as follows:

Implementing a simple subject/observer pattern
Implement aspect-oriented design
Implement event-driven architecture

The basic architecture allows you to add and remove listeners for specific events, either on an instance basis or in a shared collection; trigger events; and terminate listener execution.

Quick Start

Typically, you will create an EventManager within a class.

Copy code The code is as follows:

use ZendEventManagerEventManagerInterface;
use ZendEventManagerEventManager;
use ZendEventManagerEventManagerAwareInterface;

class Foo implements EventManagerAwareInterface
{
protected $events;

Public function setEventManager(EventManagerInterface $events)
{
          $events->setIdentifiers(array(
             __CLASS__,
              get_called_class(),
));
           $this->events = $events;
         return $this;
}

Public function getEventManager()
{
If (null === $this->events) {
                $this->setEventManager(new EventManager());
}
          return $this->events;
}
}

The above code allows the user to access the EventManager instance, or reset it with a new one; if it does not exist, it will be lazily instantiated when used.

EventManager is only interested in whether it triggered some events. The basic trigger accepts three parameters: the name of the event, which is usually the current function/method name; the context, which is usually the current object instance; and the parameters, which are usually the parameters provided to the current function/method.

Copy code The code is as follows:

class Foo
{
// ... assume events definition from above

Public function bar($baz, $bat = null)
{
          $params = compact('baz', 'bat');
            $this->getEventManager()->trigger(__FUNCTION__, $this, $params);
}
}

In order, triggering an event only cares if something is listening for the event. A listener is added to the EventManager, specifying a specific event and the callback to be notified. The callback accepts an Event object, which has accessors for getting the event name, context, and parameters. Let's add a listener and fire the event.

Copy code The code is as follows:

use ZendLogFactory as LogFactory;

$log = LogFactory($someConfig);
$foo = new Foo();
$foo->getEventManager()->attach('bar', function ($e) use ($log) {
$event = $e->getName();
$target = get_class($e->getTarget());
$params = json_encode($e->getParams());

$log->info(sprintf(
         '%s called on %s, using params %s',
         $event,
         $target,
         $params
));
});

// Results in log message:
$foo->bar('baz', 'bat');
// reading: bar called on Foo, using params {"baz" : "baz", "bat" : "bat"}"

Note that the second argument to attach() is any valid callback; the example shows an anonymous function to keep the example self-contained. However, you can also use a valid function name, a function object, a string referencing a static method, or a callback array with a specific static method or instance method. Once again, any PHP callback is valid.

Sometimes you may want to specify a listener without creating an object instance of the EventManager class. Zend Framework implements it through the concept of SharedEventCollection. Simply put, you can use a well-known SharedEventCollection to inject a standalone EventManager instance, and the EventManager instance will be queried for additional listeners. Listeners added to a SharedEventCollection are roughly the same as normal event managers; calling attach is exactly the same as EventManager, but requires an additional parameter at the beginning: a specified instance. Remember when creating an instance of EventManager, how did we pass it __CLASS__? When using a SharedEventCollection, that value, or any string in the array you provide to the constructor, may be used to identify an instance. As an example, assuming we have a SharedEventManager instance that we know has been injected into our EventManager instance (for instances, via dependency injection), we can change the above example to add via a shared collection:

Copy code The code is as follows:

use ZendLogFactory as LogFactory;

// Assume $events is a ZendEventManagerSharedEventManager instance

$log = LogFactory($someConfig);
$events->attach('Foo', 'bar', function ($e) use ($log) {
$event = $e->getName();
$target = get_class($e->getTarget());
$params = json_encode($e->getParams());

$log->info(sprintf(
         '%s called on %s, using params %s',
         $event,
         $target,
         $params
));
});

// Later, instantiate Foo:
$foo = new Foo();
$foo->getEventManager()->setSharedEventCollection($events);

// And we can still trigger the above event:
$foo->bar('baz', 'bat');
// results in log message:
// bar called on Foo, using params {"baz" : "baz", "bat" : "bat"}"

Note: StaticEventManager

In 2.0.0beta3, you can use StaticEventManager singleton as a SharedEventCollection. This way, you don't need to worry about where or how to access the SharedEventCollection; it's globally available by simply calling StaticEventManager::getInstance().

Be aware, however, that the framework deprecates its use, and in 2.0.0beta4 you will replace it by configuring a SharedEventManager instance and injecting it into a separate EventManager instance.

Wildcard Listener

Sometimes you may want to add the same listener for many or all events of a given instance, or perhaps, use a shared event collection, many contexts, and many events. The EventManager component allows this.

Add multiple events at once

Copy code The code is as follows:

$events = new EventManager();
$events->attach(array('these', 'are', 'event', 'names'), $callback);

Add

via wildcard

Copy code The code is as follows:

$events = new EventManager();
$events->attach('*', $callback);

Note that if you specify a priority, that priority will be used for any events fired by this listener.

The code above specifies that any time a trigger is triggered will result in a notification for this specific listener.

Add multiple events at once through a SharedEventManager

Copy code The code is as follows:

$events = new SharedEventManager();
// Attach to many events on the context "foo"
$events->attach('foo', array('these', 'are', 'event', 'names'), $callback);

// Attach to many events on the contexts "foo" and "bar"
$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 specified events.

Add all events at once via a SharedEventManager

Copy code The code is as follows:

$events = new SharedEventManager();
// Attach to all events on the context "foo"
$events->attach('foo', '*', $callback);

// Attach to all events on the contexts "foo" and "bar"
$events->attach(array('foo', 'bar'), '*', $callback);

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

The above code specifies the context "foo" and "bar", and the specified listener will be notified when any event is triggered.

Configuration Options

EventManager Options

Identifier

The string or array of strings that the given EventManager instance can answer when accessed via a SharedEventManager.

event_class

The name of an alternative Event class used to represent events passed to listeners.

shared_collections

A SharedEventCollection instance when the event is triggered.

Available methods

__construct

__construct(null|string|int Sidentifier)

Constructs a new EventManager instance, using the given identifier, if provided, for the purpose of sharing the collection.

setEventClass

setEventClass(string $class)

Provides a replacement Event class name to use when creating events that are passed to triggered listeners.

setSharedCollections

setSharedCollections(SharedEventCollection $collections=null)

A SharedEventCollection instance used when an event is triggered.

getSharedCollections

getSharedCollections()

Returns the SharedEventCollection instance currently added to. If no collection is added, returns empty, or a SharedEventCollection instance.

trigger

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

Trigger all listeners for the specified event. It is recommended to use the current function/method name for $event, followed by ".pre", ".post", etc., if necessary. $context should be an instance of the current object, or the name of the function if it is not triggered using an object. $params should usually be an associative array or ArrayAccess instance; we recommend using parameters passed to functions/methods (compact() is often useful here). This method can also accept a callback and behaves the same as triggerUntil().

The

method returns an instance of a ResponseCollection, which can be used to introspect the values ​​returned by a variety of listeners, test for short-circuiting, and more.

triggerUntil

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

Trigger all listeners for the specified event, just like trigger(), except that it passes the return value of each listener to $callback; if $callback returns a boolean true value, the execution of the listener will be terminated. You can use $result->stopped() to test this.

attach

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

Add $callback to the EventManager instance to listen for the event $event. If a $priority is provided, the listener will be inserted into the internal listener stack using that priority; higher values ​​will be executed first. (The default priority is "1", and runs with negative values.)

The

method returns an instance of ZendStdlibCallbackHandler; this value can be passed to detach() later, if needed.

attachAggregate

attachAggregate(string|ListenerAggregate $aggregate)

If a string is passed as $aggregate, instantiate that class. $aggregate is then passed to the attach() method of the EventManager instance so it can register the listener.

Return ListenerAggregate instance.

detach

detach(CallbackHandler $listener)

Scan all listeners and cancel any listeners matching $listener so they will no longer be triggered.

Returns a true boolean if any listener has been assigned and unsubscribed, otherwise returns a false boolean.

detachAggregate

detachAggregate(ListenerAggregate $aggregate)

Loop through all events to determine which listener the collection represents; for all matches, the listener will be removed.

Returns a true boolean if any listener is identified and unsubscribed, otherwise returns a false boolean.

getEvents

getEvent()

Returns an array with the names of all events attached to the listener.

getListeners

getListeners(string $event)

Returns a ZendStdlibPriorityQueue instance for all listeners added to $event

clearListeners

clearListeners(string $event)

Remove all listeners added to $event.

prepareArgs

prepareArgs(array $args)

Creates an ArrayObject from the provided $args. This is useful if you want your listener to be able to change parameters so that later listeners or triggered methods can see these changes.

zend framework 2 introductory learning and communication

I’d like to lend you your precious space and give me an answer to exchange and learn about zend framework 2. Come here, there are a little more people. Group number 213966183

For the module setting problem of zend framework 20

It’s good to know

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/861791.htmlTechArticleZend Framework 2.0 Event Manager (The EventManager) introductory tutorial, zendeventmanager Overview EventManger is a tool designed for the following use cases Component: Copy the code as follows:...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template