The Observer pattern helps objects talk to each other when something changes. It makes sure many parts can update automatically without being tightly connected.
Observer pattern in PHP
<?php interface Observer { public function update(string $message): void; } interface Subject { public function attach(Observer $observer): void; public function detach(Observer $observer): void; public function notify(): void; } class ConcreteSubject implements Subject { private array $observers = []; private string $state = ''; public function attach(Observer $observer): void { $this->observers[] = $observer; } public function detach(Observer $observer): void { $this->observers = array_filter( $this->observers, fn($obs) => $obs !== $observer ); } public function notify(): void { foreach ($this->observers as $observer) { $observer->update($this->state); } } public function setState(string $state): void { $this->state = $state; $this->notify(); } } class ConcreteObserver implements Observer { private string $name; public function __construct(string $name) { $this->name = $name; } public function update(string $message): void { echo "Observer {$this->name} received update: {$message}\n"; } } ?>
The Subject keeps a list of Observer objects and notifies them when needed.
Observers implement an update method to receive messages or data changes.
<?php // Create subject and observers $subject = new ConcreteSubject(); $observer1 = new ConcreteObserver('A'); $observer2 = new ConcreteObserver('B'); // Attach observers $subject->attach($observer1); $subject->attach($observer2); // Change state and notify observers $subject->setState('Hello Observers!'); ?>
<?php // Detach an observer $subject->detach($observer1); // Change state again $subject->setState('Second update'); ?>
This program shows the Observer pattern in action. Two observers listen to the subject. When the subject changes, both get notified. Then one observer is removed, and only the remaining observer gets the next update.
<?php interface Observer { public function update(string $message): void; } interface Subject { public function attach(Observer $observer): void; public function detach(Observer $observer): void; public function notify(): void; } class ConcreteSubject implements Subject { private array $observers = []; private string $state = ''; public function attach(Observer $observer): void { $this->observers[] = $observer; } public function detach(Observer $observer): void { $this->observers = array_filter( $this->observers, fn($obs) => $obs !== $observer ); } public function notify(): void { foreach ($this->observers as $observer) { $observer->update($this->state); } } public function setState(string $state): void { $this->state = $state; $this->notify(); } } class ConcreteObserver implements Observer { private string $name; public function __construct(string $name) { $this->name = $name; } public function update(string $message): void { echo "Observer {$this->name} received update: {$message}\n"; } } // Create subject and observers $subject = new ConcreteSubject(); $observer1 = new ConcreteObserver('A'); $observer2 = new ConcreteObserver('B'); // Attach observers $subject->attach($observer1); $subject->attach($observer2); // Change state and notify observers $subject->setState('Hello Observers!'); // Detach one observer $subject->detach($observer1); // Change state again $subject->setState('Second update'); ?>
Make sure to detach observers when they no longer need updates to avoid memory leaks.
The pattern helps keep code organized and easy to change.
The Observer pattern lets objects watch and react to changes in another object.
It helps keep parts of your program loosely connected and easy to update.
Use it when many things need to know about changes in one place.
Practice
Observer pattern in PHP programming?Solution
Step 1: Understand the Observer pattern concept
The Observer pattern is designed to let one object notify others about changes.Step 2: Match the purpose with the options
To allow objects to watch and react to changes in another object correctly describes this notification and reaction mechanism.Final Answer:
To allow objects to watch and react to changes in another object -> Option AQuick Check:
Observer pattern = objects watch and react [OK]
- Confusing Observer with database or input handling
- Thinking it speeds up code execution
- Mixing it with unrelated design patterns
Solution
Step 1: Recall the standard method to add observers
In PHP's Observer pattern, the subject callsattach()to add observers.Step 2: Verify method and object roles
The subject manages observers, so$subject->attach($observer);is correct.Final Answer:
$subject->attach($observer); -> Option CQuick Check:
Subject attaches observer = $subject->attach($observer) [OK]
- Calling attach() on observer instead of subject
- Using non-standard method names like addObserver
- Mixing up subject and observer roles
$subject = new Subject();
$observer = new ConcreteObserver();
$subject->attach($observer);
$subject->setState('Hello');
Assuming
ConcreteObserver prints the new state when notified.Solution
Step 1: Understand the flow of notification
The subject changes state and notifies the observer, which prints the new state.Step 2: Identify the observer's reaction
The observer prints the state 'Hello' when notified.Final Answer:
Hello -> Option AQuick Check:
Observer prints new state = Hello [OK]
- Assuming no output without calling notify explicitly
- Confusing printed message with generic text
- Expecting errors without method definitions
class Subject {
private $observers = [];
public function attach($observer) {
$this->observers[] = $observer;
}
public function notify() {
foreach ($this->observers as $observer) {
$observer->update();
}
}
}
$subject = new Subject();
$subject->notify();
Solution
Step 1: Check observer attachment before notify
The code calls notify() without attaching any observers first.Step 2: Understand effect of no observers
Since no observers are attached, notify() loops over an empty array and does nothing.Final Answer:
No observers attached before notify is called -> Option DQuick Check:
Notify without observers = no action [OK]
- Thinking private array causes error
- Assuming attach() method is missing
- Believing notify() should not call update()
Solution
Step 1: Identify how to support multiple reactions
Different observer classes allow each to react uniquely to the same notification.Step 2: Evaluate options for flexibility and design
Create different observer classes implementing a common interface and attach them to the subject uses a common interface but different classes, which is clean and scalable.Final Answer:
Create different observer classes implementing a common interface and attach them to the subject -> Option BQuick Check:
Multiple observers = different classes with common interface [OK]
- Using one observer with complex if-else logic
- Attaching only one observer limits reactions
- Ignoring design principles by using globals
Ready to prove it?
Pass the test and this pattern moves unknown
