laravel中的事件处理

一、什么是事件处理

      事件就是在特地时间、特定地点、发生的特定行为。例如:删除某个用户帖子这个行为后,要通过站短发送信息给帖子所属的用户。这里就有删除帖子事件,发站短是事件后处理。

二、为什么要使用事件机制(有那些优点)

      事件机制是一种很好的应用解耦方式,一个事件可以拥有多个互补依赖的监听器。如用户对某个帖子进行回帖操作后,就可以触发给用户发积分、加金币、清除帖子详情页对varnish缓存、给楼主发送push提醒、同步数据到一uid取模分表对业务上... 。回帖后需要处理对这些业务互补干扰,分属在不同模块,一些服务对业务逻辑还可以进行异步处理,如给楼主发送push提醒。所以事件机制可以解藕,让类承担单一职责,代码变的更清晰、易于维护。

三、该如何使用事件

      laravel事件机制主要有注册事件、事件、监听器、事件分发等部分组成。

      1、注册事件和监听器

       在模块目录下等providers目录下类EventServiceProvider.php的$listen数组包含所有事件(键)和事件所对应监听器(值)来注册事件的监听器,例如我们添加一个添加课程是给用户发送站短

     /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        LessonJoined::class => [NotifyUserForLessonJoined::class]
    ];
  2、生成事件和监听器

        将事件和监听器放在服务提供者EventServiceProvider.php之后,可以使用命令event:generate在模块下的events、listens目录下生成相对于的事件和监听器

     3、定义事件

       在模块的events目录中新增事件类

<?php
namespace Education\LiveLesson\Events;

use Meijiabang\Events\Event;

class LessonJoined extends Event
{
}
     4、定义监听者

在模块的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;
    }
}
View Code
     5、分发事件

     如果要分发事件,你可以将事件实例传递给辅助函数 event。这个函数将会把事件分发到所有已经注册的监听器上。因为辅助函数 event 是全局可访问的,所以你可以在应用中的任何地方调用它:

event(new LessonJoined($privilege));

 

转载于:https://www.cnblogs.com/wenxianguo/p/9059905.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值