Zend Framework 2.0事件管理器(The EventManager)入门教程,zendeventmanager
Zend Framework 2.0事件管理器(The EventManager)入门教程,zendeventmanager
概述
EventManger是一个为以下使用情况设计的组件:
复制代码 代码如下:
实现简单的主题/观察者模式
实现面向切面的设计
实现事件驱动的架构
基本的架构允许你添加和解除指定事件的侦听器,无论是在一个实例基础还是一个共享的集合;触发事件;终止侦听器的执行。
快速入门
通常,你将会在一个类中创建一个EventManager。
复制代码 代码如下:
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;
}
}
上面的代码允许用户访问EventManager实例,或使用一个新的实例重置它;如果不存在,它将会在被用到的时候惰性实例化。
EventManager仅仅对它是否触发了一些事件感兴趣。基础的触发接受三个参数:事件的名字,它通常是当前的函数/方法名;上下文,它通常是当前的对象的实例;和参数,它通常是提供给当前函数/方法的参数。
复制代码 代码如下:
class Foo
{
// ... assume events definition from above
public function bar($baz, $bat = null)
{
$params = compact('baz', 'bat');
$this->getEventManager()->trigger(__FUNCTION__, $this, $params);
}
}
按顺序,触发事件仅关心否有一些东西侦听了事件。侦听器添加到EventManager,指定一个指定的事件和要通知的回调。回调接受一个Event对象,它有一个用于获取事件名字,上下文和参数的访问器。让我们添加一个侦听器,并且触发事件。
复制代码 代码如下:
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"}"
注意,attach()的第二个参数是一个任何有效的回调;例子中展示了一个匿名函数来保持例子是自包含的。然而,你同样可以使用一个有效的函数名字,一个函数对象,一个引用静态方法的字符串,或一个带有一个指定静态方法或实例方法的回调数组。再一次,任何PHP回调都是有效的。
有时候你可能想要指定一个侦听器没有一个创建了一个EventManager的类的对象实例。Zend Framework通过一个SharedEventCollection的概念来实现它。简单的说,你可以使用一个众所周知的SharedEventCollection来注入一个独立的EventManager实例,并且EventManager实例将会为附加的侦听器来查询它。添加到SharedEventCollection的侦听器与正常的事件管理器大略相同;调用attach与EventManager完全相同,但是在开始需要一个附加的参数:一个指定的实例。还记得创建一个EventManager的实例,我们是如何传递给他__CLASS__的?在使用一个SharedEventCollection时,那个值,或者任何你提供给构造器的数组中的任何字符串,可能用于识别一个实例。作为一个示例,假设我们有一个SharedEventManager实例我们知道已经被注入到我们的EventManager实例中了(对于实例,通过依赖注入),我们可以更改上面的例子来通过共享集合来添加:
复制代码 代码如下:
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"}"
注意:StaticEventManager
在2.0.0beta3中,你可以使用StaticEventManager单例作为一个SharedEventCollection。这样,你不需要担心在哪或者如何来访问SharedEventCollection;它通过简单的调用StaticEventManager::getInstance()是全局可用的。
要知道,然而,框架不赞成它的使用,并且在2.0.0beta4中,你将通过配置一个SharedEventManager实例并注入到一个单独的EventManager实例中来代替它。
通配符侦听器
有时候你可能会想要为一个给定的实例的很多事件或全部事件添加相同的侦听器,或者可能,使用一个共享事件集合,很多上下文,并且很多事件。EventManager组件允许这样做。
一次添加多个事件
复制代码 代码如下:
$events = new EventManager();
$events->attach(array('these', 'are', 'event', 'names'), $callback);
通过通配符添加
复制代码 代码如下:
$events = new EventManager();
$events->attach('*', $callback);
注意如果你指定了一个优先级,那个优先级将会用于这个侦听器触发的任何事件。
上面的代码指定的是任何时间触发将会导致这个特定侦听器的通知。
通过一个SharedEventManager一次添加多个事件
复制代码 代码如下:
$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);
注意如果你指定了一个优先级,那个优先级将会被用于所有指定的事件。
通过一个SharedEventManager一次添加所有事件
复制代码 代码如下:
$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);
注意如果你指定了一个优先级,那个优先级将会被用于所有指定的事件。
上面的代码指定了上下文“foo”和“bar”,指定的侦听器将会在任何事件触发时被通知。
配置选项
EventManager选项
标识符
给定的EventManager实例可以回答的字符串或字符串数组,当通过一个SharedEventManager访问时。
event_class
一个替代的Event类的名字用于代表传给侦听器的事件。
shared_collections
当触发事件时的一个SharedEventCollection实例。
可用方法
__construct
__construct(null|string|int Sidentifier)
构造一个新的EventManager实例,使用给定的标识符,如果提供了的话,为了共享集合的目的。
setEventClass
setEventClass(string $class)
提供替换Event类的名字用在创建传递给触发的侦听器的事件时。
setSharedCollections
setSharedCollections(SharedEventCollection $collections=null)
用于触发事件时的SharedEventCollection实例。
getSharedCollections
getSharedCollections()
返回当前添加到的SharedEventCollection实例。如果没有添加集合,返回空,或者一个SharedEventCollection实例。
trigger
trigger(string $event, mixed $target, mixed $argv, callback $callback)
触发指定事件的所有侦听器。推荐为$event使用当前的函数/方法名,在后面加上诸如“.pre”、“.post”等,如果有需要的话。$context应该是当前对象的实例,或者是函数的名字如果不是使用对象触发。$params通常应该是一个关联数组或者ArrayAccess实例;我们推荐使用传递给函数/方法的参数(compact()在这里通常很有用处)。这个方法同样可以接受一个回调并且表现与triggerUntil()相同。
方法返回一个ResponseCollection的实例,它可以用于反省各种各样的侦听器返回的值,测试短路,以及更多。
triggerUntil
triggerUntil(string $event, mixed $context, mixed $argv, callback $callback)
触发指定事件的所有侦听器,就像trigger(),额外的是它将每个侦听器的返回值传递给$callback;如果$callback返回一个布尔true值,侦听器的执行将被终止。你可以使用$result->stopped()来测试它。
attach
attach(string $event, callback $callback, int $priority)
添加$callback到EventManager实例,侦听事件$event。如果提供了一个$priority,侦听器将会使用那个优先级插入到内部的侦听器堆栈;高的值会先执行。(默认的优先级是“1”,并且运行使用负的值。)
方法返回一个Zend\Stdlib\CallbackHandler的实例;这个值可以在稍后传递给detach(),如果需要的话。
attachAggregate
attachAggregate(string|ListenerAggregate $aggregate)
如果一个字符串被传递作为$aggregate,实例化那个类。$aggregate然后被传递给EventManager实例的attache()方法因此他可以注册侦听器。
返回ListenerAggregate实例。
detach
detach(CallbackHandler $listener)
扫描所有的侦听器,并且取消匹配$listener的所有侦听器因此它们将不再会被触发。
返回一个true布尔值如果任何侦听器已经被指定并且取消订阅,否则返回一个false布尔值。
detachAggregate
detachAggregate(ListenerAggregate $aggregate)
循环所有的事件来确定集合代表的侦听器;对于所有的匹配项,侦听器将会被移除。
如果任何侦听器被确定并被取消订阅返回一个true布尔值,否则返回一个false布尔值。
getEvents
getEvent()
返回一个有侦听器附加的所有事件名字的数组。
getListeners
getListeners(string $event)
返回一个添加到$event的所有侦听器的Zend\Stdlib\PriorityQueue实例
clearListeners
clearListeners(string $event)
移除添加到$event的所有侦听器。
prepareArgs
prepareArgs(array $args)
从提供的$args创建一个ArrayObject。如果你想要你的侦听器可以更改参数让稍后的侦听器或触发的方法可以看到这些更改的情况下着将很有用。
zend framework 2 入门学习及交流
借你的宝地跟一个回答,zend framework 2 交流学习,来这里吧,人稍微多点。群号213966183
对于zend framework 20 的module设置的问题
知道就好

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

.NET Framework 4 is required by developers and end users to run the latest versions of applications on Windows. However, while downloading and installing .NET Framework 4, many users complained that the installer stopped midway, displaying the following error message - " .NET Framework 4 has not been installed because Download failed with error code 0x800c0006 ". If you are also experiencing it while installing .NETFramework4 on your device then you are at the right place

Whenever your Windows 11 or Windows 10 PC has an upgrade or update issue, you will usually see an error code indicating the actual reason behind the failure. However, sometimes confusion can arise when an upgrade or update fails without an error code being displayed. With handy error codes, you know exactly where the problem is so you can try to fix it. But since no error code appears, it becomes challenging to identify the issue and resolve it. This will take up a lot of your time to simply find out the reason behind the error. In this case, you can try using a dedicated tool called SetupDiag provided by Microsoft that helps you easily identify the real reason behind the error.
![SCNotification has stopped working [5 steps to fix it]](https://img.php.cn/upload/article/000/887/227/168433050522031.png?x-oss-process=image/resize,m_fill,h_207,w_330)
As a Windows user, you are likely to encounter SCNotification has stopped working error every time you start your computer. SCNotification.exe is a Microsoft system notification file that crashes every time you start your PC due to permission errors and network failures. This error is also known by its problematic event name. So you might not see this as SCNotification having stopped working, but as bug clr20r3. In this article, we will explore all the steps you need to take to fix SCNotification has stopped working so that it doesn’t bother you again. What is SCNotification.e

Microsoft Windows users who have installed Microsoft.NET version 4.5.2, 4.6, or 4.6.1 must install a newer version of the Microsoft Framework if they want Microsoft to support the framework through future product updates. According to Microsoft, all three frameworks will cease support on April 26, 2022. After the support date ends, the product will not receive "security fixes or technical support." Most home devices are kept up to date through Windows updates. These devices already have newer versions of frameworks installed, such as .NET Framework 4.8. Devices that are not updating automatically may

It's been a week since we talked about the new safe mode bug affecting users who installed KB5012643 for Windows 11. This pesky issue didn't appear on the list of known issues Microsoft posted on launch day, thus catching everyone by surprise. Well, just when you thought things couldn't get any worse, Microsoft drops another bomb for users who have installed this cumulative update. Windows 11 Build 22000.652 causes more problems So the tech company is warning Windows 11 users that they may experience problems launching and using some .NET Framework 3.5 applications. Sound familiar? But please don't be surprised

PHP implementation framework: ZendFramework introductory tutorial ZendFramework is an open source website framework developed by PHP and is currently maintained by ZendTechnologies. ZendFramework adopts the MVC design pattern and provides a series of reusable code libraries to serve the implementation of Web2.0 applications and Web Serve. ZendFramework is very popular and respected by PHP developers and has a wide range of

How to use ACL (AccessControlList) for permission control in Zend Framework Introduction: In a web application, permission control is a crucial function. It ensures that users can only access the pages and features they are authorized to access and prevents unauthorized access. The Zend framework provides a convenient way to implement permission control, using the ACL (AccessControlList) component. This article will introduce how to use ACL in Zend Framework

According to news on December 9, Cooler Master recently demonstrated a mini chassis kit in cooperation with notebook modular solution provider Framework at a demonstration event at the Taipei Compute Show. The unique thing about this kit is that it can be compatible with and Install the motherboard from the framework notebook. Currently, this product has begun to be sold on the market, priced at 39 US dollars, which is equivalent to approximately 279 yuan at the current exchange rate. The model number of this chassis kit is named "frameWORKMAINBOARDCASE". In terms of design, it embodies the ultimate compactness and practicality, measuring only 297x133x15 mm. Its original design is to be able to seamlessly connect to framework notebooks
