Zend Framework 2.0 Event Manager (the EventManager) introductory tutorial _php instance

Source: Internet
Author: User
Tags compact instance method sprintf zend zend framework

Overview

Eventmanger is a component designed for the following uses:

Copy Code code as follows:

Achieve a simple theme/observer pattern
To realize the design of plane-facing
Implementing event-driven schemas

The basic architecture allows you to add and deallocate listeners for the specified event, whether it is on an instance basis or a shared collection, triggers an event, and terminates the execution of the listener.

Quick Start

Typically, you will create a eventmanager in a class.

Copy Code code as follows:

Use Zend\eventmanager\eventmanagerinterface;
Use Zend\eventmanager\eventmanager;
Use Zend\eventmanager\eventmanagerawareinterface;

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 resets it with a new instance, and if it does not exist, it will be lazily instantiated when it is used.

EventManager is only interested in whether it triggers a few events. The underlying trigger accepts three parameters: the name of the event, which is usually the current function/method name, the context, which is usually an instance of the current object, and a parameter that is usually supplied to the current function/method.

Copy Code code 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 events only care about whether there is something listening to the event. The listener is added to the EventManager, specifying a specified event and a callback to notify. The callback accepts an event object that has an accessor to get the event name, context, and parameters. Let's add a listener and trigger the event.

Copy Code code as follows:

Use Zend\log\factory 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 parameter of attach () is a valid callback; an anonymous function is shown in the example to keep the example self-contained. However, you can also use a valid function name, a function object, a string that references a static method, or an array of callbacks with a specified static method or instance method. Again, any PHP callback is valid.

Sometimes you might want to specify that a listener does not have an object instance that creates a EventManager class. The Zend framework implements it through a sharedeventcollection concept. Simply put, you can use a well-known sharedeventcollection to inject a separate EventManager instance, and the EventManager instance will query it for the attached listener. The listener added to the sharedeventcollection is roughly the same as the normal event manager; The call attach is identical to EventManager, but an additional parameter is required at the beginning: a specified instance. Remember to create an instance of EventManager, how did we pass it on to him __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, suppose we have a sharedeventmanager instance that we know has been injected into our EventManager instance (for instance, through dependency injection), we can change the example above to add it through a shared collection:

Copy Code code as follows:

Use Zend\log\factory as logfactory;

Assume $events is a Zend\eventmanager\sharedeventmanager 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 the Staticeventmanager as a single example as a sharedeventcollection. In this way, you do not need to worry about where or how to access the sharedeventcollection; it is globally available through a simple invocation of staticeventmanager::getinstance ().

You know, however, the framework does not approve of its use, and in 2.0.0beta4 you will replace it by configuring a Sharedeventmanager instance and injecting it into a single eventmanager instance.

Wildcard listeners

Sometimes you might want to add the same listener to many or all of the events for a given instance, or maybe use a shared event set, many contexts, and many events. The EventManager component allows this to be done.

Add multiple events at once

Copy Code code as follows:

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

Add with wildcard characters

Copy Code code as follows:

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

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

The above code specifies that any time trigger will cause this particular listener to be notified.

Add multiple Events One Sharedeventmanager at a time

Copy Code code as follows:

$events = new Sharedeventmanager ();
Attach to many events in 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 one Sharedeventmanager at a time

Copy Code code as follows:

$events = new Sharedeventmanager ();
Attach to all events in 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 given EventManager instance can answer a string or an array of strings when accessed through a sharedeventmanager.

Event_class

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

Shared_collections

An sharedeventcollection instance when an event is triggered.

Available methods

__construct

__construct (Null|string|int sidentifier)

Constructs a new EventManager instance, using the given identifier, if provided, in order to share the purpose of the collection.

Seteventclass

Seteventclass (String $class)

Provides the substitution of the name of the event class when creating an event that is passed to the triggered listener.

Setsharedcollections

Setsharedcollections (sharedeventcollection $collections =null)

The sharedeventcollection instance to use when triggering the event.

Getsharedcollections

Getsharedcollections ()

Returns the Sharedeventcollection instance that is currently being added. If no collection is added, returns NULL, or a sharedeventcollection instance.

Trigger

Trigger (String $event, mixed $target, mixed $argv, callback $callback)

Triggers all listeners for the specified event. It is recommended that you use the current function/method name for $event, followed by ". Pre", ". Post", and so on, if necessary. $context should be an instance of the current object, or the name of the function if it is not triggered by using an object. $params should usually be an associative array or an arrayaccess instance; We recommend using parameters passed to the function/method (the compact () is often useful here). This method can also accept a callback and behave in the same way as Triggeruntil ().

method returns an instance of a responsecollection that can be used to reflect on the values returned by various listeners, test short circuits, and more.

Triggeruntil

Triggeruntil (String $event, mixed $context, mixed $argv, callback $callback)

Triggers all listeners for the specified event, like Trigger (), which, in addition, passes the return value of each listener to $callback, and if $callback returns a Boolean true value, the listener's execution is terminated. You can use $result->stopped () to test it.

Attach

Attach (String $event, callback $callback, int $priority)

Add $callback to EventManager instances and listen for event $event. If a $priority is provided, the listener will use that priority to insert into the inner listener stack, and the high value will be executed first. (The default priority is "1" and runs with negative values.) )

method returns an instance of the Zend\stdlib\callbackhandler, which can be passed to detach () at a later time, if necessary.

Attachaggregate

Attachaggregate (string| Listeneraggregate $aggregate)

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

Returns the Listeneraggregate instance.

Detach

Detach (CallbackHandler $listener)

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

Returns a Boolean value of TRUE if any listener has been specified and the subscription is canceled, a false Boolean value is returned.

Detachaggregate

Detachaggregate (Listeneraggregate $aggregate)

Loops all events to determine which listeners the collection represents, and for all occurrences, the listener is removed.

Returns a Boolean value of False if any listener is determined and the unsubscribe returns a true Boolean value.

GetEvents

GetEvent ()

Returns an array of all the event names attached to the listener.

Getlisteners

Getlisteners (String $event)

Returns a Zend\stdlib\priorityqueue instance of all listeners added to the $event

Clearlisteners

Clearlisteners (String $event)

Removes all listeners added to the $event.

Prepareargs

Prepareargs (Array $args)

Creates a arrayobject from the provided $args. It would be useful if you wanted your listener to change the parameters so that later listeners or triggered methods can see these changes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.