designs2 / event-dispatcher
Contao开源CMS的事件分发服务
Requires
- php: >=5.3
- contao-community-alliance/composer-plugin: ~2.0
- contao-community-alliance/dependency-container: ~1.6
- contao/core: >=2.11,<4-dev
- symfony/event-dispatcher: ~2.3
Requires (Dev)
Replaces
- bit3/contao-event-dispatcher: 1.3.0
This package is not auto-updated.
Last update: 2024-10-02 10:26:02 UTC
README
 
Contao开源CMS的事件分发器
为什么需要为Contao开源CMS开发事件分发器,钩子不是足够吗?首先,你需要明白,钩子和事件之间没有真正的区别。它们都是系统内部的 notifications。
但事件比钩子更灵活。它们可以在层次结构中传递、消费、停止或冒泡。
Contao存在事件分发器的真正重大原因
- 事件 是软件设计中的标准范式。
- 钩子 是一种改变软件行为的范式,它并不是为 notifications 而设计的。
- 钩子只是事件的一种特殊形式。
- 基于 symfony event dispatcher 的扩展被广泛使用。
- 事件分发器可以处理所有形式的回调,如闭包或静态方法。
监听事件
事件分发器提供了两种监听事件的方式。
第一种,也是最常用的,是事件监听器。它被设计成监听单个事件。
第二种是事件订阅者,它被设计成监听多个事件。
按配置定义事件监听器
从版本 1.3 开始,有两种方式可以按配置定义您的监听器。
/config/event_listeners.php
我们推荐使用这种方法!
文件 /config/event_listeners.php
必须返回一个数组,键是事件名,值是监听器。
<?php return array( // With a closure 'event-name' => array( function($event) { // event code } ), // With a static callable 'event-name' => array( array('MyEventListener', 'myCallable') ), // With an object callable 'event-name' => array( array(new MyEventListener(), 'myCallable') ), // With a service object 'event-name' => array( array($GLOBALS['container']['my_event_listener'], 'myCallable') ), // You can wrap the listener into an array with a priority 'event-name' => array( array($listener, $priority) ), );
/config/config.php
在您的 /config/config.php
中,使用 $GLOBALS['TL_EVENTS']
注册您的事件处理程序。
使用闭包
$GLOBALS['TL_EVENTS']['event-name'][] = function($event) { // event code };
使用静态可调用
$GLOBALS['TL_EVENTS']['event-name'][] = array('MyEventListener', 'myCallable');
使用对象可调用
$GLOBALS['TL_EVENTS']['event-name'][] = array(new MyEventListener(), 'myCallable');
按优先级处理
要定义优先级,可以使用一个数组,其中第一个元素是监听器,第二个元素是优先级。
$GLOBALS['TL_EVENTS']['event-name'][] = array($listener, $priority);
按代码定义事件监听器
$container['event-dispatcher']->addListener('event-name', $listener);
按配置定义事件订阅者
从版本 1.3 开始,有两种方式可以按配置定义您的监听器。
/config/event_subscribers.php
我们推荐使用这种方法!
文件 /config/event_subscribers.php
必须返回一个订阅者数组。
<?php return array( // With a factory function($eventDispatcher) { return new MyEventSubscriber(); }, // With an object class name 'MyEventSubscriber', // With an object instance new MyEventSubscriber(), // With a service object $GLOBALS['container']['my_event_subscriber'], );
/config/config.php
在您的 /config/config.php
中,使用 $GLOBALS['TL_EVENT_SUBSCRIBERS']
注册您的订阅者。
使用工厂
$GLOBALS['TL_EVENT_SUBSCRIBERS'][] = function($eventDispatcher) { return new MyEventSubscriber(); };
使用对象类名
$GLOBALS['TL_EVENT_SUBSCRIBERS'][] = 'MyEventSubscriber';
使用对象实例
$GLOBALS['TL_EVENT_SUBSCRIBERS'][] = new MyEventSubscriber();
按代码分的事件订阅者
$container['event-dispatcher']->addSubscriber(new MyEventSubscriber());