Event-Driven Architecture
Events decouple your application components. When a post is published, you might notify subscribers, update search, and post to social media — without the Post model knowing about any of it.
Creating Events and Listeners
php artisan make:event PostPublished
php artisan make:listener NotifySubscribers --event=PostPublished
class PostPublished
{
use Dispatchable, SerializesModels;
public function __construct(public Post $post) {}
}
class NotifySubscribers implements ShouldQueue
{
public function handle(PostPublished $event): void
{
Subscriber::active()->each(function ($sub) use ($event) {
Mail::to($sub->email)->queue(new NewPostMail($event->post));
});
}
}
Registering Listeners
// In AppServiceProvider
Event::listen(PostPublished::class, NotifySubscribers::class);
Event::listen(PostPublished::class, IndexPostForSearch::class);
Dispatching Events
PostPublished::dispatch($post);
Model Observers
For Eloquent lifecycle hooks:
php artisan make:observer PostObserver --model=Post
class PostObserver
{
public function created(Post $post): void
{
Cache::forget('recent_posts');
}
public function updated(Post $post): void
{
Cache::forget("post_{$post->slug}");
Cache::forget('sitemap_xml');
}
public function deleted(Post $post): void
{
Cache::forget("post_{$post->slug}");
}
}
// Register in AppServiceProvider
Post::observe(PostObserver::class);
Events and observers make your code open to extension without modification — the Open/Closed Principle in action.