Observer Pattern
What Is It?
The Observer Pattern defines a one-to-many dependency between objects. When one object (subject) changes state, all its dependents (observers) are notified and updated automatically.
Why?
Without observers, you must call multiple dependent methods directly in the subject. This couples the subject to all its dependents and makes adding new reactions difficult.
When to Use
When a single action needs to trigger multiple side effects: creating a user triggers welcome email, analytics event, default settings creation. Eloquent Observers are a Laravel-specific implementation.
When Not to Use
When the side effects are always the same and few. When you need explicit control over execution order. When performance is critical and you want synchronous processing.
Example
Example
<?php
// Eloquent Observer
class PostObserver
{
public function __construct(
private Cache $cache,
private SearchIndex $search
) {}
public function created(Post $post): void
{
// Auto-index for search
$this->search->index($post);
// Clear list cache
$this->cache->forget('posts:all');
// Notify author's followers
$this->notifyFollowers($post);
}
public function updated(Post $post): void
{
if ($post->isDirty('status') && $post->status === 'published') {
event(new PostPublished($post));
}
$this->cache->forget('posts:all');
$this->search->update($post);
}
public function deleted(Post $post): void
{
$this->cache->forget('posts:all');
$this->search->remove($post);
}
}
// Register
Post::observe(PostObserver::class);
// Events (also observer pattern)
class UserCreated
{
use Dispatchable, SerializesModels;
public function __construct(public User $user) {}
}
class SendWelcomeEmail
{
public function handle(UserCreated $event): void
{
Mail::to($event->user)->send(new WelcomeMail());
}
}
event(new UserCreated($user)); // Notifies all listeners
Pros
- Loose coupling between subject and observers
- Dynamic subscription at runtime
- Multiple reactions to a single event
- Easy to add new observers without changing the subject
- Laravel has built-in support (Eloquent events, Event system)
Cons
- Observers are not aware of each other
- Can be hard to debug when many observers fire
- Order of notification is not guaranteed
- Memory leaks if observers are not properly cleaned up
- Overkill for simple one-to-one dependencies