Usage Summary of laravel event system

Time:2021-9-12

Laravel’s event provides a simple observer implementation, which can subscribe to and listen to various events in the application. The event classes are saved in the app / events directory, and the listeners of these events are saved in the app / listeners directory. These directories are automatically created only when you use the artisan command to generate events and listeners.

Event mechanism is a good application decoupling method, because an event can have multiple independent listeners. For example, if you want to send a slack notification to users every time an order is shipped. You can simply initiate an ordershipped event and let the listener convert it into a slack notification after receiving it, so that you don’t have to couple the business code of the order with the code of the slack notification.

Generate an event class

For example, generate a Userlogin event through the artist command:

php artisan make:event UserLogin

In APP / events, a userlogin.php file will be automatically generated, with few contents, as follows:

<?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');
    }
}

Define listener

An event can be monitored by one or more listeners, that is, observer mode. We can define multiple listeners and execute a series of logic when the event occurs.

Events and listeners can be defined in $listen of eventserviceprovider, as follows:

protected $listen = [
    'App\Events\UserLogin' => [
        'App\Lisenter\DoSomething1',
        'App\Lisenter\Dosomething2',
    ],
];

Then execute the artist command to automatically generate listeners in the app / listener directory.

php artisan make:event generate

You can see that dosomething1.php and dosomething2.php are added to the app / reader directory. Let’s take a look at one of them:

<?php
 
namespace App\Lisenter;
 
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');
    }
}

In the handle method of the two listeners, we print a log to test it, as shown in the code handle method.

Distribute and trigger events

We distribute events in the method of a controller, that is, trigger events to see whether the listener works normally.

In a word:

event(new UserLogin());

Then we asked the controller to observe the log and found that the log was printed:

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

Then the event monitoring mechanism will work normally.

Queue asynchronous processing

If a listener needs to perform slow operations, it can be placed in the message queue for asynchronous processing.

For example, if dosomething1 above is changed to be put into the queue, only the implements shoulqueue interface is required.

class DoSomething1 implements ShouldQueue

You can also specify a queue driver, as shown in the following code.

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

We execute the controller method again.

Do something1 is not printed in the log, only do something2 is printed, but a list named queues: default is found in the redis queue.

{"job":"Illuminate\\Events\\[email protected]","data":{"class":"App\\Listener\\DoSomething1","method":"handle","data":"a:1:{i:0;O:20:\"App\\Events\\UserLogin\":1:{s:6:\"socket\";N;}}"},"id":"3D7VDUwueYGtUvsazicWsifwWQxnnLID","attempts":1}

At this time, you need to use PHP artisan queue: work to execute the queue task, which is the handle method of dosomething1 listener.

Reference link

(original address:https://blog.tanteng.me/2018/…