事件就是在特意时间、特定地点、发生的特定行为。例如:删除某个用户帖子这个行为后,要经过站短发送信息给帖子所属的用户。这里就有删除帖子事件,发站短是事件后处理。php
事件机制是一种很好的应用解耦方式,一个事件能够拥有多个互补依赖的监听器。如用户对某个帖子进行回帖操做后,就能够触发给用户发积分、加金币、清除帖子详情页对varnish缓存、给楼主发送push提醒、同步数据到一uid取模分表对业务上... 。回帖后须要处理对这些业务互补干扰,分属在不一样模块,一些服务对业务逻辑还能够进行异步处理,如给楼主发送push提醒。因此事件机制能够解藕,让类承担单一职责,代码变的更清晰、易于维护。laravel
laravel事件机制主要有注册事件、事件、监听器、事件分发等部分组成。数组
在模块目录下等providers目录下类EventServiceProvider.php的$listen数组包含全部事件(键)和事件所对应监听器(值)来注册事件的监听器,例如咱们添加一个添加课程是给用户发送站短缓存
/** * The event listener mappings for the application. * * @var array */ protected $listen = [ LessonJoined::class => [NotifyUserForLessonJoined::class] ];
将事件和监听器放在服务提供者EventServiceProvider.php以后,可使用命令event:generate在模块下的events、listens目录下生成相对于的事件和监听器app
在模块的events目录中新增事件类less
<?php namespace Education\LiveLesson\Events; use Meijiabang\Events\Event; class LessonJoined extends Event { }
在模块的listeners目录中新增监听类异步
<?php namespace Education\LiveLesson\Listeners; use Meijiabang\Support\Exception\ExceptionCode; use Education\LiveLesson\Events\LessonJoined; use Education\LiveLesson\Services\LessonService; use Illuminate\Support\Facades\Log; use Meijiabang\Events\Listener; use User\Notice\Services\NoticeService; class NotifyUserForLessonJoined extends Listener { /** * @var string */ protected $content = '参加《[name]》课程成功,记得按时参加课程>'; /** * @param LessonJoined $event * @return bool */ public function handle(LessonJoined $event) { $model = $event->getModel(); if (!is_null($model)) { $noticeService = new NoticeService($model->uid, NoticeService::LIVELESSON_JOIN); $lessonName = app(LessonService::class)->find($model->relation_id)->title; $serviceResult = $noticeService->send([ 'lesson_id' => $model->relation_id, 'uid' => $model->uid, 'content' => str_replace('[name]', $lessonName, $this->content), ]); if (ExceptionCode::SUCCESS != $serviceResult->getCode()) { Log::info(date("Y-m-d H:i:s") . ' Failed to send live-lesson-join message to ' . $model->uid); return true; } } return true; } }
若是要分发事件,你能够将事件实例传递给辅助函数 event。这个函数将会把事件分发到全部已经注册的监听器上。由于辅助函数 event 是全局可访问的,因此你能够在应用中的任何地方调用它:ide
event(new LessonJoined($privilege));