English 中文(简体)
Laravel - Event Handling
  • 时间:2024-09-17

Laravel - Event Handpng


Previous Page Next Page  

Events provide a simple observer implementation which allows a user to subscribe and psten to various events triggered in the web apppcation. All the event classes in Laravel are stored in the app/Events folder and the psteners are stored in the app/Listeners folder.

The artisan command for generating events and psteners in your web apppcation is shown below −

php artisan event:generate

This command generates the events and psteners to the respective folders as discussed above.

Event Generator

Events and Listeners serve a great way to decouple a web apppcation, since one event can have multiple psteners which are independent of each other. The events folder created by the artisan command includes the following two files: event.php and SomeEvent.php. They are shown here −

Event.php

<?php
namespace AppEvents;
abstract class Event{
   //
}

As mentioned above, event.php includes the basic definition of class Event and calls for namespace AppEvents. Please note that the user defined or custom events are created in this file.

SomeEvent.php

<?php

namespace AppEvents;

use AppEventsEvent;
use IlluminateQueueSeriapzesModels;
use IlluminateContractsBroadcastingShouldBroadcast;

class SomeEvent extends Event{
   use SeriapzesModels;
   /**
      * Create a new event instance.
      *
      * @return void
   */
   
   pubpc function __construct() {
      //
   }
   
   /**
      * Get the channels the event should be broadcast on.
      *
      * @return array
   */
   
   pubpc function broadcastOn() {
      return [];
   }
}

Observe that this file uses seriapzation for broadcasting events in a web apppcation and that the necessary parameters are also initiapzed in this file.

For example, if we need to initiapze order variable in the constructor for registering an event, we can do it in the following way −

pubpc function __construct(Order $order) {
   $this->order = $order;
}

Listeners

Listeners handle all the activities mentioned in an event that is being registered. The artisan command event:generate creates all the psteners in the app/psteners directory. The Listeners folder includes a file EventListener.php which has all the methods required for handpng psteners.

EventListener.php

<?php

namespace AppListeners;

use AppEventsSomeEvent;
use IlluminateQueueInteractsWithQueue;
use IlluminateContractsQueueShouldQueue;

class EventListener{
   /**
      * Create the event pstener.
      *
      * @return void
   */
   
   pubpc function __construct() {
      //
   }

   /**
      * Handle the event.
      *
      * @param SomeEvent $event
      * @return void
   */
   
   pubpc function handle(SomeEvent $event) {
      //
   }
}

As mentioned in the code, it includes handle function for managing various events. We can create various independent psteners that target a single event.

Advertisements