Example Analysis of Laravel Event Listener Usage

  • 2021-11-29 23:20:27
  • OfStack

This article illustrates the use of Laravel event listeners. Share it for your reference, as follows:

Here is a best practice scenario, which is divided into the following steps:

Step 1: Register events and listeners.

In the EventServiceProvider linsten array plus events and listeners, the key name is the event, the key value inside the array is one or more listeners, meaning that when a certain event occurs, it is transmitted to those listeners in the array to perform a series of operations.

Here, I listen to the event of sending SMS verification code. Once there is an action of sending verification code, I will add a piece of data to the verification code sending record table for recording.

D:\phpStudy\WWW\BCCKidV1.0\app\Providers\EventServiceProvider.php


protected $listen = [
  'App\Events\Event' => [
    'App\Listeners\EventListener',
  ],
  'App\Events\SendPhoneCodeEvent' => [
    'App\Listeners\SendPhoneCodeListener',
  ],
];

Step 2: Generate listening and event files.


php artisan event:generate

The following two files are automatically generated:

D:\phpStudy\WWW\BCCKidV1.0\app\Events\SendPhoneCodeEvent.php
D:\phpStudy\WWW\BCCKidV1.0\app\Listeners\SendPhoneCodeListener.php

Step 3: Open App\ Events\ SendPhoneCodeEvent,

Add an attribute, which is an array, which will contain information such as the content of the verification code and the mobile phone number receiving the verification code.


public $data;
public function __construct($data)
{
  $this->data = $data;
}

Step 4: Set the operation that needs to be performed in the listener. Here I will insert a record directly.


public function handle(SendPhoneCodeEvent $event)
{
  AuthCode::create($event->data);
}

Step 5: Trigger the event.


use App\Events\SendPhoneCodeEvent;
...
$data = [
  'findBy' => $findBy,
  'auth_code' => $code,
  'customer_id' => $customer_id,
  'expire_time' => date('Y-m-d H:i:s', time() + 300),
];
# Trigger event 
event(new SendPhoneCodeEvent($data));

My own thoughts:

1. The function of an event can actually be replaced by a method. You can refer to 1 where you need to call, and then execute this method. However, events have the advantage that they are handled by queue by default, and can be used to perform time-consuming operations, such as sending mail, sending verification codes and so on.

2. The code is neat and looks comfortable for 1 point.

For more readers interested in Laravel related content, please check the topics on this site: "Introduction and Advanced Tutorial of Laravel Framework", "Summary of Excellent Development Framework of php", "Introduction Tutorial of php Object-Oriented Programming", "Introduction Tutorial of php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Laravel framework.


Related articles: