## 事件系统
事件提供了一个简单的观察者实现,能够订阅和监听应用中发生的各种事件。事件类通常存放在`app/Events`目录下,而这些事件类的监听器则存放在`app/Listeners`目录下。
事件系统为应用各个方面的解耦提供了非常棒的方法,因为单个事件可以拥有多个互不依赖的监听器。举个例子,你可能希望每次订单发货时向用户推送一个 Slack 通知。你可以简单地发起一个可以被监听器接收并转化为 Slack 通知的`OrderShipped`事件,而不是将订单处理代码和 Slack 通知代码耦合在一起。
事件定义:
```php
namespace App\Events;
/**
* 订单支付成功
*
* Class OrderPaySuccessEvent
* @package App\Events
*/
class OrderPaySuccessEvent extends Event
{
protected $name = 'order.pay.success.action';
public $order;
public function __construct($order = [])
{
$this->order = $order;
}
}
```
监听器定义:
```php
namespace App\Listeners;
use App\Events\OrderPaySuccessEvent;
/**
* 支付异步通知
* Class PayAsyncNotifyListener
*
* @package App\Listeners
*/
class PayAsyncNotifyListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
}
/**
* 执行事件
*
* @param OrderPaySuccessEvent $event
*
* @throws \Fend_Exception
*/
public function handle( OrderPaySuccessEvent $event )
{
$order = $event->order;
// 业务逻辑代码...
}
}
```
逻辑处理写在 `handle` 方法即可。
事件与监听器的配置在`app\Providers\EventServiceProvider.php` 文件。
具体示例:
```php
namespace App\Providers;
use App\Events\Event;
use App\Fend\ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* 应用程序的事件监听器映射
*
* @var array
*/
protected $listen = [
// 商品下单完成事件
// OrderCreateCompleteEvent::class => [
// AppOrderCreateCompleteListener::class,
// WechatOrderCreateCompleteListener::class,
// ],
// 示例事件
'example.action' => [
\App\Listeners\ExampleListener::class,
\App\Listeners\WangleleListener::class,
],
// 订单创建成功
'order.create.complete.action' => [
],
// 订单支付成功通知
'order.pay.success.action' => [
\App\Listeners\PowerAddListener::class,
\App\Listeners\GiftReceiveListener::class,
\App\Listeners\PayAsyncNotifyListener::class, // 异步通知监听器放在最后
],
// 订单退款成功通知
'order.refund.success.action' => [
\App\Listeners\PowerRemoveListener::class,
],
// 兑换卡激活成功通知
'rechargecard.actived.action' => [
\App\Listeners\RechargeCard\RechargeListener::class,
\App\Listeners\RechargeCard\SendGiftListener::class,
],
// 学习卡激活成功通知
'studycard.actived.action' => [
\App\Listeners\StudyCard\RechargeListener::class,
\App\Listeners\StudyCard\SendGiftListener::class,
\App\Listeners\StudyCard\ActivityListener::class,
],
];
/**
* The subscriber classes to register.
*
* @var array
*/
protected $subscribe = [];
/**
* Register the application's event listeners.
*
* @return void
*/
public function boot()
{
$events = $this->app['events'];
foreach ($this->listen as $event => $listeners) {
foreach ($listeners as $listener) {
$events->addListener($event, [new $listener, 'handle']);
}
}
foreach ($this->subscribe as $subscriber) {
$events->addSubscriber($subscriber);
}
}
/**
* {@inheritdoc}
*/
public function register()
{
//
}
/**
* Get the events and handlers.
*
* @return array
*/
public function listens()
{
return $this->listen;
}
}
```