laravel 事件机制 实践总结
观察者模式
- 在EventServiceProvider的linsten数组里面加上事件和监听器,键名是事件,键值里面的数组是一个或者多个监听器,
protected $listen = [
'AppEventsEvent' => [
'AppListenersEventListener',
],
'AppEventsSendPhoneCodeEvent' => [
'AppListenersSendPhoneCodeListener',
],
];
- 生成监听和事件文件 php artisan event:generate
- 编辑Event类
- 编辑Listener类
- 触发事件 调用全局函数event(),传入事件对象;
- event(new SendPhoneCodeEvent($data));
发布订阅模式
<?php
/**
* Created by PhpStorm.
* User: liutengfei
* Date: 2018/12/25
* Time: 18:45
*/
namespace AppListeners;
use AppEventsSomeEvent;
use AppEventsTestEvent;
class TaskToLogListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
public function someEventTask(SomeEvent $event)
{
echo 'uuuu'."
" ;
}
public function testEventTask(TestEvent $event)
{
echo 'iiioo'."
";
}
//这里是订阅中心,这里既可以调用自己,也可以分发到其他监听者
public function subscribe($events)
{
$events->listen('AppEventsSomeEvent','AppListenersTaskToLogListener@someEventTask');
$events->listen('AppEventsTestEvent','AppListenersTest2Listener@Handel');
$events->listen('AppEventsTestEvent','AppListenersTest1Event@Handel');
}
}
- 在EventServiceProvider添加属性$subscribe
- protected $subscribe = [TaskToLogListener::class];
- 触发事件
Event::fire(new TaskAdded($task));
Event::fire(new TaskDeled($task));