Laravel - Event Handling

Laravel - Event Handling

Events provide a simple observer implementation that allows a user to subscribe to and listen for various events fired in a web application. All event classes in Laravel are stored in app/Events folder and listeners are stored in app/Listeners folder .

The artisan command to generate events and listeners in your web application is shown below −

php artisan event:generate

This command generates events and listeners for the respective folders as described above.

Events and listeners are a great way to decouple a web application because a single event can have multiple listeners that are independent of each other. The events folder created by the artisan command contains the following two files: event.php and SomeEvent.php. They are shown here −

event.php

<? php
 namespace App \Events ; abstract class Event { // } 
  
   

As mentioned above, event.php includes a base Event class definition and calls the App\Events namespace . Please note that custom or custom events are created in this file.

SomeEvent.php

<? php

namespace App \Events ; 

use App \Events\Event ; use Illuminate \Queue\SerializesModels ; use Illuminate \Contracts\Broadcasting\ShouldBroadcast ; 
 
 

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

Note that this file uses serialization to broadcast events to the web application, and that the required parameters are also initialized in this file.

For example, if we need to initialize an order variable in the constructor to register an event, we can do it like this:

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

Listeners

Listeners handle all actions mentioned in the event that is being registered. The artisan : generate command event creates all the listeners in the app/listeners directory . The Listeners folder contains the EventListener.php file, which contains all the methods needed to process listeners.

EventListener.php

<? php

namespace App \Listeners ; 

use App \Events\SomeEvent ; use Illuminate \Queue\InteractsWithQueue ; use Illuminate \Contracts\Queue\ShouldQueue ; 
 
 

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

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

As mentioned in the code, it includes a handle function to handle various events. We can create different independent listeners that target the same event.