Laravel Model Events - I'm a bit confused about where they're meant to go

后端 未结 9 790
长发绾君心
长发绾君心 2020-12-07 13:15

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

I have a Model called Article. I wish to send email alert

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 13:50

    In your case, you may also use following approach:

    // Put this code in your Article Model
    
    public static function boot() {
    
        parent::boot();
    
        static::created(function($article) {
            Event::fire('article.created', $article);
        });
    
        static::updated(function($article) {
            Event::fire('article.updated', $article);
        });
    
        static::deleted(function($article) {
            Event::fire('article.deleted', $article);
        });
    }
    

    Also, you need to register listeners in App\Providers\EventServiceProvider:

    protected $listen = [
        'article.created' => [
            'App\Handlers\Events\ArticleEvents@articleCreated',
        ],
        'article.updated' => [
            'App\Handlers\Events\ArticleEvents@articleUpdated',
        ],
        'article.deleted' => [
            'App\Handlers\Events\ArticleEvents@articleDeleted',
        ],
    ];
    

    Also make sure you have created the handlers in App\Handlers\Events folder/directory to handle that event. For example, article.created handler could be like this:

    mailer = $mailer;
        }
    
        public function articleCreated(Article $article)
        {
            // Implement mailer or use laravel mailer directly
            $this->mailer->notifyArticleCreated($article);
        }
    
        // Other Handlers/Methods...
    }
    

提交回复
热议问题