laravel Event and Listener Instance Code

  • 2021-12-05 05:52:30
  • OfStack

Introduction

The last article realized the record user access, the design is flawed, the code is tightly coupled in the middleware. If subsequent modifications require not only recording ip and cities, but also recording data to new data tables or other statistics, it is unreasonable to keep adding and modifying codes. At this time, you can use Laravel's event/listener for processing. The code can be seen in GitHub.

Event/listener

Laravel Events provides a simple observer mode implementation that allows you to subscribe to and listen for events in your application.

Observer mode, sometimes referred to as publish/subscribe mode, is used to implement publish/subscribe functions for objects: 1 When the state of the principal object changes, the observer object associated with it will be notified and act accordingly.

The above is a brief description of the event/listener and observer mode. Combined with this requirement understanding, when a user access event is triggered, its observer handles it. There can be multiple observers, and this example only does the warehousing operation.

Create an event/listener

Add an event/listener to the app/Providers/EventServiceProvider. php file as follows


 /**
   * The event listener mappings for the application.
   *
   * @var array
   */
  protected $listen = [
    Registered::class => [
      SendEmailVerificationNotification::class,
    ],
    'App\Events\UserBrowse' => [
      'App\Listeners\CreateBrowseLog',
      //  Other listeners 
    ],
  ];

Once added, execute php artisan event: generate and the corresponding event/listener will be created automatically. Two files, app/Events/UserBrowse. php and app/Listeners/CreateBrowseLog. php, were created.

Implementation code

Focus on the event app/Events/UserBrowse. php file, where you need to receive data for subsequent processing, as follows


  public $ip_addr;
  public $request_url;
  public $city_name;

  /**
   * Create a new event instance.
   *
   * @return void
   */
  public function __construct($ip_addr, $request_url, $city_name)
  {
    $this->ip_addr = $ip_addr;
    $this->request_url = $request_url;
    $this->city_name = $city_name;
  }

Then there is the listener app/Listeners/CreateBrowseLog. php. What we want to do here is to put the data received in the event into storage. The code is as follows


/**
   * Handle the event.
   *
   * @param UserBrowse $event
   * @return void
   */
  public function handle(UserBrowse $event)
  {
    $log = new \App\Models\BrowseLog();

    $log->ip_addr = $event->ip_addr;
    $log->request_url = $event->request_url;
    $log->city_name = $event->city_name;

    $log->save();
  }

Distribution event

Finally, there is the distribution event, modifying the code of app/Http/Middleware/BrowseLog. php middleware as follows


/**
   * Handle an incoming request.
   *
   * @param \Illuminate\Http\Request $request
   * @param \Closure $next
   * @return mixed
   */
  public function handle($request, Closure $next)
  {
    //  Use Events / Listener storage 
    event(new UserBrowse($request->getClientIp(), $request->path(), get_city_by_ip(false, 'null')));
    
    return $next($request);
  }

There is no problem after the test.

Conclusion

This modification, from the sensory point of view, is to transfer the warehousing operation from middleware to listener, but the actual significance is far more than that. For example, the same event can be distributed in different places; Event adds requirements, only need to add 1 listener; Queues and so on can also be used in listeners.


Related articles: