pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

Laravel 模型事件 - 我對(duì)它們的去向有點(diǎn)困惑

Laravel Model Events - I#39;m a bit confused about where they#39;re meant to go(Laravel 模型事件 - 我對(duì)它們的去向有點(diǎn)困惑)
本文介紹了Laravel 模型事件 - 我對(duì)它們的去向有點(diǎn)困惑的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!

問(wèn)題描述

所以我認(rèn)為一個(gè)好的 Laravel 應(yīng)用程序應(yīng)該是非常模型驅(qū)動(dòng)和事件驅(qū)動(dòng)的.

So the way I see it is that a good Laravel application should be very model- and event-driven.

我有一個(gè)名為 Article 的模型.我希望在發(fā)生以下事件時(shí)發(fā)送電子郵件警報(bào):

I have a Model called Article. I wish to send email alerts when the following events happen:

  • 何時(shí)創(chuàng)建文章
  • 文章更新時(shí)
  • 當(dāng)文章被刪除時(shí)

文檔說(shuō)我可以使用模型事件并在 <AppProvidersEventServiceProvider的code>boot()函數(shù).

The docs say I can use Model Events and register them within the boot() function of AppProvidersEventServiceProvider.

但這讓我很困惑,因?yàn)?..

But this is confusing me because...

  • 當(dāng)我添加其他模型(如 CommentAuthor)時(shí),會(huì)發(fā)生什么,這些模型需要所有自己的模型事件的完整集合?EventServiceProvider 的單個(gè) boot() 函數(shù)會(huì)非常龐大??嗎?
  • Laravel 的其他"事件的目的是什么?如果實(shí)際上我的事件只會(huì)響應(yīng)模型 CRUD 操作,為什么我還需要使用它們?
  • What happens when I add further models like Comment or Author that need full sets of all their own Model Events? Will the single boot() function of EventServiceProvider just be absolutely huge?
  • What is the purpose of Laravel's 'other' Events? Why would I ever need to use them if realistically my events will only respond to Model CRUD actions?

我是 Laravel 的初學(xué)者,來(lái)自 CodeIgniter,所以我試圖圍繞正確的 Laravel 做事方式進(jìn)行思考.感謝您的建議!

I am a beginner at Laravel, having come from CodeIgniter, so trying to wrap my head around the proper Laravel way of doing things. Thanks for your advice!

推薦答案

最近我在我的 Laravel 5 項(xiàng)目之一中遇到了同樣的問(wèn)題,我不得不在其中記錄所有模型事件.我決定使用 Traits.我創(chuàng)建了 ModelEventLogger Trait 并簡(jiǎn)單地用于所有需要記錄的模型類.我將根據(jù)您的需要更改它,如下所示.

Recently I came to same problem in one of my Laravel 5 project, where I had to log all Model Events. I decided to use Traits. I created ModelEventLogger Trait and simply used in all Model class which needed to be logged. I am going to change it as per your need Which is given below.

<?php

namespace AppTraits;

use IlluminateDatabaseEloquentModel;
use IlluminateSupportFacadesEvent;

/**
 * Class ModelEventThrower 
 * @package AppTraits
 *
 *  Automatically throw Add, Update, Delete events of Model.
 */
trait ModelEventThrower {

    /**
     * Automatically boot with Model, and register Events handler.
     */
    protected static function bootModelEventThrower()
    {
        foreach (static::getModelEvents() as $eventName) {
            static::$eventName(function (Model $model) use ($eventName) {
                try {
                    $reflect = new ReflectionClass($model);
                    Event::fire(strtolower($reflect->getShortName()).'.'.$eventName, $model);
                } catch (Exception $e) {
                    return true;
                }
            });
        }
    }

    /**
     * Set the default events to be recorded if the $recordEvents
     * property does not exist on the model.
     *
     * @return array
     */
    protected static function getModelEvents()
    {
        if (isset(static::$recordEvents)) {
            return static::$recordEvents;
        }

        return [
            'created',
            'updated',
            'deleted',
        ];
    }
} 

現(xiàn)在您可以在要為其拋出事件的任何模型中使用此特征.在您的情況下 Article 模型.

Now you can use this trait in any Model you want to throw events for. In your case in Article Model.

<?php namespace App;

use AppTraitsModelEventThrower;
use IlluminateDatabaseEloquentModel;

class Article extends Model {

    use ModelEventThrower;

    //Just in case you want specific events to be fired for Article model
    //uncomment following line of code

   // protected static $recordEvents = ['created'];

}

現(xiàn)在在您的 app/Providers/EventServiceProvider.php 中,在 boot() 方法中為 Article 注冊(cè)事件處理程序.

Now in your app/Providers/EventServiceProvider.php, in boot() method register Event Handler for Article.

 public function boot(DispatcherContract $events)
 {
     parent::boot($events);
     $events->subscribe('AppHandlersEventsArticleEventHandler');
 }

現(xiàn)在在app/Handlers/Events目錄下創(chuàng)建ArticleEventHandler類,

<?php namespace AppHandlersEvents;

use AppArticle;

class ArticleEventHandler{

    /**
     * Create the event handler.
     *
     * @return AppHandlersEventsArticleEventHandler
     */
    public function __construct()
    {
        //
    }

    /**
    * Handle article.created event
    */

   public function created(Article $article)
   {
      //Implement logic
   }

   /**
   * Handle article.updated event
   */

   public function updated(Article $article)
   {
      //Implement logic
   }

  /**
  * Handle article.deleted event
  */

  public function deleted(Article $article)
  {
     //Implement logic
  }

 /**
 * @param $events
 */
 public function subscribe($events)
 {
     $events->listen('article.created',
            'AppHandlersEventsArticleEventHandler@created');
     $events->listen('article.updated',
            'AppHandlersEventsArticleEventHandler@updated');
     $events->listen('article.deleted',
            'AppHandlersEventsArticleEventHandler@deleted');
 }

}

正如您從不同的答案中看到的,來(lái)自不同的用戶,處理模型事件的方法不止一種.還有自定義事件,可以在Events文件夾中創(chuàng)建,可以在Handler文件夾中處理,可以從不同的地方分派.希望能幫到你.

As you can see from different answers, from different Users, there are more than 1 way of handling Model Events. There are also Custom events That can be created in Events folder and can be handled in Handler folder and can be dispatched from different places. I hope it helps.

這篇關(guān)于Laravel 模型事件 - 我對(duì)它們的去向有點(diǎn)困惑的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

Laravel Eloquent Union query(Laravel Eloquent Union 查詢)
Overwrite laravel 5 helper function(覆蓋 Laravel 5 輔助函數(shù))
laravel querybuilder how to use like in wherein function(laravel querybuilder 如何在 where 函數(shù)中使用 like)
The Response content must be a string or object implementing __toString(), quot;booleanquot; given after move to psql(響應(yīng)內(nèi)容必須是實(shí)現(xiàn) __toString()、“boolean和“boolean的字符串或?qū)ο?移動(dòng)到 psql 后給出) - IT屋-程
Roles with laravel 5, how to allow only admin access to some root(Laravel 5 的角色,如何只允許管理員訪問(wèn)某些根)
Laravel Auth - use md5 instead of the integrated Hash::make()(Laravel Auth - 使用 md5 而不是集成的 Hash::make())
主站蜘蛛池模板: 天津次氯酸钠酸钙溶液-天津氢氧化钠厂家-天津市辅仁化工有限公司 | 气体检测仪-氢气检测仪-可燃气体传感器-恶臭电子鼻-深国安电子 | 100_150_200_250_300_350_400公斤压力空气压缩机-舰艇航天配套厂家 | T恤衫定做,企业文化衫制作订做,广告T恤POLO衫定制厂家[源头工厂]-【汉诚T恤定制网】 | 老房子翻新装修,旧房墙面翻新,房屋防水补漏,厨房卫生间改造,室内装潢装修公司 - 一修房屋快修官网 | 全自动包装秤_全自动上袋机_全自动套袋机_高位码垛机_全自动包装码垛系统生产线-三维汉界机器(山东)股份有限公司 | 泰兴市热钻机械有限公司-热熔钻孔机-数控热熔钻-热熔钻孔攻牙一体机 | 脱硝喷枪-氨水喷枪-尿素喷枪-河北思凯淋环保科技有限公司 | 盐城网络公司_盐城网站优化_盐城网站建设_盐城市启晨网络科技有限公司 | SF6环境监测系统-接地环流在线监测装置-瑟恩实业 | 成都APP开发-成都App定制-成都app开发公司-【未来久】 | 上海办公室设计_办公楼,写字楼装修_办公室装修公司-匠御设计 | 北京租车牌|京牌指标租赁|小客车指标出租 | 高光谱相机-近红外高光谱相机厂家-高光谱成像仪-SINESPEC 赛斯拜克 | 天津热油泵_管道泵_天津高温热油泵-天津市金丰泰机械泵业有限公司【官方网站】 | led全彩屏-室内|学校|展厅|p3|户外|会议室|圆柱|p2.5LED显示屏-LED显示屏价格-LED互动地砖屏_蕙宇屏科技 | 网架支座@球铰支座@钢结构支座@成品支座厂家@万向滑动支座_桥兴工程橡胶有限公司 | 石磨面粉机|石磨面粉机械|石磨面粉机组|石磨面粉成套设备-河南成立粮油机械有限公司 | 自动记录数据电子台秤,记忆储存重量电子桌称,设定时间记录电子秤-昆山巨天 | Maneurop/美优乐压缩机,活塞压缩机,型号规格,技术参数,尺寸图片,价格经销商 | 沈阳建筑设计公司_加固改造设计_厂房设计_设计资质加盟【金辉设计】 | 生物制药洁净车间-GMP车间净化工程-食品净化厂房-杭州波涛净化设备工程有限公司 | 浙江红酒库-冰雕库-气调库-茶叶库安装-医药疫苗冷库-食品物流恒温恒湿车间-杭州领顺实业有限公司 | 滑板场地施工_极限运动场地设计_滑板公园建造_盐城天人极限运动场地建设有限公司 | 不锈钢发酵罐_水果酒发酵罐_谷物发酵罐_山东誉诚不锈钢制品有限公司 | 政府园区专业委托招商平台_助力企业选址项目快速落地_东方龙商务集团 | 精密线材测试仪-电线电缆检测仪-苏州欣硕电子科技有限公司 | 昆山PCB加工_SMT贴片_PCB抄板_线路板焊接加工-昆山腾宸电子科技有限公司 | 全国国际化学校_国际高中招生_一站式升学择校服务-国际学校网 | 工业rfid读写器_RFID工业读写器_工业rfid设备厂商-ANDEAWELL | 硬齿面减速机_厂家-山东安吉富传动设备股份有限公司 | 东莞工厂厂房装修_无尘车间施工_钢结构工程安装-广东集景建筑装饰设计工程有限公司 | 建筑资质代办-建筑企业资质代办机构-建筑资质代办公司 | 专业的新乡振动筛厂家-振动筛品质保障-环保振动筛价格—新乡市德科筛分机械有限公司 | 釜溪印象网络 - Powered by Discuz! | 蜘蛛车-登高车-高空作业平台-高空作业车-曲臂剪叉式升降机租赁-重庆海克斯公司 | 昆明网络公司|云南网络公司|昆明网站建设公司|昆明网页设计|云南网站制作|新媒体运营公司|APP开发|小程序研发|尽在昆明奥远科技有限公司 | 电磁铁_推拉电磁铁_机械手电磁吸盘电磁铁厂家-广州思德隆电子公司 | 泡沫消防车_水罐消防车_湖北江南专用特种汽车有限公司 | 粉末包装机,拆包机厂家,价格-上海强牛包装机械设备有限公司 | bng防爆挠性连接管-定做金属防爆挠性管-依客思防爆科技 |