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

后端 未结 9 815
长发绾君心
长发绾君心 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:55

    You've tagged this question as Laravel 5, so I would suggest not using model events as you'll end up with lots of extra code in your models which may make things difficult to manage in future. Instead, my recommendation would be to make use of the command bus and events.

    Here's the docs for those features:

    http://laravel.com/docs/5.0/bus

    http://laravel.com/docs/5.0/events

    My recommendation would be to use the following pattern.

    • You create a form which submits to your controller.
    • Your controller dispatches the data from the request generated to a command.
    • Your command does the heavy lifting - i.e. creates an entry in the database.
    • Your command then fires an event which can be picked up by an event handler.
    • Your event handler does something like send an email or update something else.

    There are a few reasons why I like this pattern: Conceptually your commands handle things that are happening right now and events handle things that have just happened. Also, you can easily put command and event handlers onto a queue to be processed later on - this is great for sending emails as you tend not to want to do that in real time as they slow the HTTP request down a fair bit. You can also have multiple event handlers for a single event which is great for separating concerns.

    It would be difficult to provide any actual code here as your question more about the concepts of Laravel, so I'd recommend viewing these videos so you get a good idea of how this pattern works:

    This one describes the command bus:

    https://laracasts.com/lessons/laravel-5-events

    This one describes how events work:

    https://laracasts.com/lessons/laravel-5-commands

提交回复
热议问题