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”)
getPayload()
Gets the event data as an array.array
Array representation of the event object
EventDispatcher
TheEventDispatcher 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
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
hasListeners()
Checks if an event has any listeners.string
required
Event name
bool
True if event has listeners
getListenerCount()
Gets the number of listeners for an event.string
required
Event name
int
Number of listeners (includes wildcard matches)
clear()
Removes all event listeners.clearEvent()
Removes listeners for a specific event.string
required
Event name to clear
Wildcard Patterns
The event system supports wildcard patterns for flexible event matching.Pattern Matching
- Exact Match
- Wildcard Prefix
- Wildcard Suffix
- Match All
Broadcaster
TheBroadcaster 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
broadcast()
Broadcasts an event to a channel.string
required
Channel name
Event
required
Event to broadcast
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
- Event Naming: Use past tense for event names (e.g.,
UserRegisterednotUserRegister) - Immutability: Make event properties readonly to prevent modification
- Payload Size: Keep event payloads small - include IDs, not entire objects
- Error Handling: Wrap listener code in try-catch to prevent cascade failures
- Testing: Use
EventDispatcher::clear()between tests to avoid listener pollution