临时禁用 Laravel 的模型观察者

在开发过程中我们会遇到需要临时禁用模型监听器的情况,比如有这么一个例子:
使用定义了一个发表新闻模型的观察者:

<?php

namespace App\Observers;

use App\Test;

class AddActivitySendEmailObserviers
{
        public function created(Test $test)
        {
                //接收人邮箱
                $to = '123@qq.com';
                //抄送人邮箱
                $cc = '123@qq.com';
                //邮件页面数据
                $data= array(
                        'content' => '欢迎使用邮件发送功能!',
                );
                //邮箱标题
                $title = '您收到了一封邮件————普通发送邮件';
                //传入send方法的第一个参数为生成邮件体所用的视图名
                //第二个参数$data是要传入视图的数据
                //第三个参数为闭包,允许你为邮件配置各种选项
                Mail::send('email', $data, function($message) use($title,$to,$cc){
                        //from-发件人;to-收件人,cc-抄送人;attach-附件
                        $message->from(env('MAIL_USERNAME'), '天才');
                        $message->to($to);
                        $message->cc($cc)->subject($title);
                });
        }
}

它监听了一个 created 事件,即在发表新闻后给用户发个短信。
在做假数据填充时,我们是不想要给用户发短信的,这时候我们就希望能临时禁用掉观察者。
在 Laravel 模型里其实已经预留了一个方法:Model::unsetEventDispatcher(); 可以移除事件调度器。

Test::unsetEventDispatcher();
Test::create($data);
本作品采用《CC 协议》,转载必须注明作者和本文链接
不要轻易放弃。学习成长的路上,我们长路漫漫,只因学无止境 Don't give up easily. On the way of learning and growing up, we have a long way to go, just because there is no end to learning.
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 1

这不是临时,是当前进程永久移除,后面的监听全都不见了。

所以你需要的应该是:

$dispatcher = Test::getEventDispatcher();

Test::unsetEventDispatcher();
Test::create($data);

Test::setEventDispatcher($dispatcher);
5年前 评论

这不是临时,是当前进程永久移除,后面的监听全都不见了。

所以你需要的应该是:

$dispatcher = Test::getEventDispatcher();

Test::unsetEventDispatcher();
Test::create($data);

Test::setEventDispatcher($dispatcher);
5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!