What It Is
The Observer pattern lets one object announce events to many subscribers without knowing who they are. Subscribers register once; from then on, every event reaches all of them automatically.
The publisher depends only on a small subscriber interface — new kinds of listeners appear without one line changing in the publisher. PHP even ships ready-made SplSubject and SplObserver interfaces for this pattern; a small interface of your own, as below, reads just as well.
Example: One Alert, Every Subscriber
The monitor keeps a list of subscribers. When something happens, it notifies the whole list — an email alert and a dashboard, today; a chat message tomorrow, by just subscribing it.
Publish once, deliver to all
One alert() call, two deliveries. The monitor has no idea what an email or a dashboard is — it only knows things that can be notified.
Output: PHP script
<?php
interface Subscriber {
public function notify(string $event): void;
}
class EmailAlert implements Subscriber {
public function __construct(private string $addr) {}
public function notify(string $event): void {
echo "email to ", $this->addr, ": ", $event, "\n";
}
}
class Dashboard implements Subscriber {
public function notify(string $event): void {
echo "dashboard shows: ", $event, "\n";
}
}
// The publisher keeps a list and notifies everyone on it.
class Monitor {
/** @var Subscriber[] */
private array $subscribers = [];
public function subscribe(Subscriber $s): void {
$this->subscribers[] = $s;
}
public function alert(string $event): void {
foreach ($this->subscribers as $s) {
$s->notify($event);
}
}
}
$monitor = new Monitor();
$monitor->subscribe(new EmailAlert("ops@example.com"));
$monitor->subscribe(new Dashboard());
$monitor->alert("disk almost full");
When to Use It
Use it when several parts must react to the same events and the list of reactors changes — UI updates, alerting, cache invalidation, activity feeds.
Skip it when exactly one, fixed receiver exists — call it directly. An event dispatcher in a larger PHP application is this same pattern grown up: named events, many listeners, one dispatch point.
Pros and Cons
Pros: publisher and subscribers stay decoupled; subscribers come and go at run time; new reactions need no publisher changes.
Cons: the flow becomes invisible — "who reacts to this?" takes searching; a slow or failing subscriber can stall the notify loop; forgotten unsubscribes leak.