dqba94619 2016-08-14 08:32
浏览 38
已采纳

关于laravel中不同雄辩事件的类似任务

I want to run a similar task on some different eloquent events in laravel.

For example Suppose I have a Question model. For my purpose, I used boot() function on the model like this :

class Question extends Model
    public static function boot ()
        {
            parent::boot();
            static::updated(function ($Question) {
                //some Tasks on $Question
            });

            static::updating(function ($Question) {
                //some Tasks on $Question
            });

            static::created(function ($Question) {
                //some Tasks on $Question
            });

            static::creating(function ($Question) {
                //some Tasks on $Question
            });
        }
 } 

As you see in all events , similar Tasks run and may have large code.
what is best and short approach to do that?

  • 写回答

1条回答 默认 最新

  • duanlu2935 2016-08-14 10:06
    关注

    You have several ways to refactor this code:

    1. Run saved() and saving() instead of the whole four events. saved() will substitute both created() and updated(), while saving() will substitute both creating() and updating().

    2. Fire a the same job inside all of them:

      public static function boot ()
      {
            Question::saved(function ($question) {
               dispatch(new \App\Jobs\job($question));
            });
      }
      
    3. Add the code to protected function inside the class (this is the least recommended)

    By the way, Model events should be placed in the boot method of a Service Provider, not the Model. Model has no boot method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度