Events

The Events class is part of the Libraries namespace and is designed to manage and handle events in the system. It provides methods to register, trigger, and process events. Below is a detailed explanation of each function and its purpose.

Funtions in Events Libraries

Property $listeners

<?php
protected static $listeners = [];
  • This is a static array that stores the list of listeners for each event.

  • Structure of $listeners:

<?php
[
    'EventName' => [
        priority => [listener1, listener2, ...],
        ...
    ],
    ...
]
  • EventName: The name of the event.

  • priority: The priority of the listener (higher numbers are executed first).

  • listener1, listener2: Callbacks or classes that handle the event.

on()

  • Purpose: Registers a listener (callback or class) for a specific event.

  • Parameters:

    • $eventName: The name of the event (e.g., 'PostsAddEvent').

    • $listener: A callback function or class name that will be executed when the event is triggered.

    • $priority: The priority of the listener (default is 0).

run()

  • Purpose: Triggers (dispatches) an event.

  • Parameters:

    • $eventName: The name of the event to trigger.

    • $payload: Data to pass to the event (can be an array, object, etc.).

runs()

  • Purpose: Triggers multiple events at once.

  • Parameters:

    • $events: An array of events and their associated data, in the format

General Workflow

  1. Registering Listeners:

    • Use the on() method to register listeners for events.

    • Listeners can be either callback functions or classes with a handle() method.

  2. Triggering Events:

    • Use the run() method to trigger a single event.

    • When an event is triggered:

      • Registered listeners are executed in order of priority.

      • If no listeners are registered, a default event class in the \App\Events namespace is checked and executed.

  3. Triggering Multiple Events:

    • Use the runs() method to trigger multiple events at once.

Example

Using basically

Using in Class

Using multiple Events

circle-check

Last updated

Was this helpful?