
Events & Listeners
Event creation, listener registration, dispatching events, event subscribers, queued listeners, broadcast events
1What is an Event in Laravel?
What is an Event in Laravel?
답변
An Event is a class that represents a significant action or occurrence that happened in the application. It serves as a data-carrying message that can be dispatched and listened to by multiple listeners in a decoupled manner. Events allow respecting the Open/Closed principle by adding behaviors without modifying existing code.
2How to create an Event and its associated Listener with Artisan?
How to create an Event and its associated Listener with Artisan?
답변
The command 'php artisan make:event' creates an Event, and 'php artisan make:listener' creates a Listener. By adding the --event=EventName option, the Listener is automatically typed to receive this Event. It's also possible to define the mapping in EventServiceProvider then run 'php artisan event:generate' to automatically generate all missing Events and Listeners.
3Where to register the mapping between Events and Listeners in Laravel?
Where to register the mapping between Events and Listeners in Laravel?
답변
The Events-Listeners mapping is done in the $listen property of EventServiceProvider (App\Providers\EventServiceProvider). Each key is the fully qualified Event class name, and the value is an array of Listeners. Since Laravel 11, it's also possible to use auto-discovery with PHP 8 attributes #[ListensTo] to avoid manual registration.
How to dispatch (trigger) an Event in Laravel?
What is the basic structure of a Listener in Laravel?
+15 면접 질문