Laravel’s events provide a simple observer implementation that can subscribe to and listen to various events occurring in the application. Events are stored in the App /Events directory, and Listeners for these Events are stored in the App /Listeners directory. These directories will only be created automatically if you use the Artisan command to generate events and listeners.

The event mechanism is a good way to decouple applications because an event can have multiple independent listeners. For example, if you want to send a Slack notification to the user every time an order is shipped. You can simply launch an OrderShipped event that the listener receives and converts to a Slack notification, so that you don’t have to couple the business code for the order with the code for the Slack notification.

Generate an event class

For example, using the artisan command to generate a UserLogin event:

php artisan make:event UserLogin
Copy the code

A userlogin. PHP file is automatically generated in app/Events.

<? php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class UserLogin { use InteractsWithSockets, SerializesModels; /** * Create a new event instance. * * @return void
     */
    public function __construct()
    {
        //
    }
 
    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name'); }}Copy the code

Defining listeners

An event can be listened to by one or more listeners, which is the observer mode. We can define multiple listeners, and when this event occurs, execute a set of logic.

In $Listen of EventServiceProvider, you can define events and listeners as follows:

protected $listen = [
    'App\Events\UserLogin'= > ['App\Listeners\DoSomething1'.'App\Listeners\Dosomething2',]];Copy the code

You can then run the artisan command to automatically generate Listeners in the app/Listeners directory.

php artisan event:generate
Copy the code

Dosomething1.php and doSomething2.php can be found on app/Listeners:

<? php namespace App\Listeners; use App\Events\UserLogin; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class DoSomething1 { /** * Create the event listener. * * @return void
     */
    public function __construct()
    {
        //
    }
 
    /**
     * Handle the event.
     *
     * @param  UserLogin  $event
     * @return void
     */
    public function handle(UserLogin $event)
    {
        info('do something1'); }}Copy the code

We test this by printing a log in the handle method of both listeners, as shown in the code Handle method.

Dispatch and trigger events

We distribute events in a controller’s method, that is, firing events, to see if the listener works.

In one sentence:

event(new UserLogin());
Copy the code

Then we request the controller, observe the log, and find that the log is printed:

[2018-06-17 10:04:29] local.INFO: do something1 [2018-06-17 10:04:29] local.INFO: do something2

Then the event-listen mechanism works.

Queue asynchronous processing

If a listener needs to perform a slow operation, it can be placed on a message queue for asynchronous processing.

For example, to change DoSomething1 above to something that needs to be put into a queue, you just need to implement ShoulQueue.

class DoSomething1 implements ShouldQueue
Copy the code

Queue drivers can also be specified as follows.

/ * * * task should be sent to the queue connection name * * @ var string | null * / public$connection = 'redis'; / * * * the name of the task should be sent to the queue * * @ var string | null * / public$queue = 'listeners';
Copy the code

We execute the controller method again.

Queues: Default The log did not print Do Something1, only do Something2, but found a list called Queues: Default inside the Redis queue.

{"job":"Illuminate\\Events\\CallQueuedHandler@call"."data": {"class":"App\\Listeners\\DoSomething1"."method":"handle"."data":"a:1:{i:0; O:20:\"App\\Events\\UserLogin\":1:{s:6:\"socket\"; N; }}"},"id":"3D7VDUwueYGtUvsazicWsifwWQxnnLID"."attempts": 1}Copy the code

The handle method of the DoSomething1 listener needs to be executed using PHP artisan Queue :work.

Refer to the link

  • Laravel 5.5 event system (https://laravel-china.org/docs/laravel/5.5/events/1318)
  • Laravel queue (https://laravel-china.org/docs/laravel/5.5/queues/1324)

(the original address: https://blog.tanteng.me/2018/06/laravel-event/)