Events & Listeners

Interview Questions: Observers, Broadcasting, and Decoupling

Q1: What is the difference between an Event and a Listener?

Event: A class that represents something that happened in the application (e.g., OrderShipped). It is a data container.

Listener: A class that handles the logic in response to the event (e.g., SendShipmentNotification). It contains the business logic.

Benefit: This decouples the code. The code firing the event doesn't need to know what happens next.

Q2: What are Model Observers?

Concept: Observers allow you to group event listeners for a model into a single class.

Methods: They hook into Eloquent lifecycle events like creating, created, updating, deleted, etc.

Use Case: Automatically generating a slug when a post is created, or deleting associated files when a user is deleted.

Q3: Explain Event Broadcasting.

Concept: Broadcasting allows you to share your server-side Laravel events with your client-side JavaScript application via WebSockets.

Mechanism: When an event is fired, Laravel pushes a payload to a driver (Pusher, Reverb) which then sends it to the browser. The frontend (using Laravel Echo) listens for these events to update the UI in real-time.