Skip to main content

Overview

The Lyger Events system provides a robust event dispatching mechanism with support for listeners, wildcards, and broadcasting. Build decoupled applications by emitting and listening to events throughout your codebase.

Class: Lyger\Events\Event

Abstract base class for all events in your application.

Creating an Event

getName()

Gets the event name based on the class name.
string
The short class name (e.g., “UserRegistered”)
Example:

getPayload()

Gets the event data as an array.
array
Array representation of the event object
Example:

EventDispatcher

The EventDispatcher manages event listeners and dispatches events to registered handlers.

listen()

Registers an event listener.
string
required
Event name or wildcard pattern (e.g., “User*”)
callable
required
Callback function to handle the event
Examples:

dispatch()

Dispatches an event to all registered listeners.
Event
required
The event instance to dispatch
array
Additional payload data
array
Array of results from all listeners
Example:

hasListeners()

Checks if an event has any listeners.
string
required
Event name
bool
True if event has listeners
Example:

getListenerCount()

Gets the number of listeners for an event.
string
required
Event name
int
Number of listeners (includes wildcard matches)
Example:

clear()

Removes all event listeners.
Example:

clearEvent()

Removes listeners for a specific event.
string
required
Event name to clear
Example:

Wildcard Patterns

The event system supports wildcard patterns for flexible event matching.

Pattern Matching

Dotted Patterns:

Broadcaster

The Broadcaster class enables event broadcasting to different channels.

channel()

Registers a broadcast channel.
string
required
Channel name or pattern
callable
required
Handler for broadcasts to this channel
Example:

broadcast()

Broadcasts an event to a channel.
string
required
Channel name
Event
required
Event to broadcast
Example:

EventServiceProvider

Abstract base class for registering events and listeners in a structured way.

Creating a Service Provider

Complete Examples

User Management System

E-commerce Order System

Application Logging System

Broadcasting Example

Advanced Patterns

Event Queueing

Conditional Listeners

Listener Priority

Listeners are called in the order they are registered. Register critical listeners first for proper execution order.

Best Practices

  1. Event Naming: Use past tense for event names (e.g., UserRegistered not UserRegister)
  2. Immutability: Make event properties readonly to prevent modification
  3. Payload Size: Keep event payloads small - include IDs, not entire objects
  4. Error Handling: Wrap listener code in try-catch to prevent cascade failures
  5. Testing: Use EventDispatcher::clear() between tests to avoid listener pollution