PHP Observer Pattern
The Observer pattern is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they're observing.
1. Concept
- Subject (Publisher): The object that has interesting state. It maintains a list of observers and notifies them when state changes.
- Observer (Subscriber): The objects that want to be notified when the Subject's state changes.
2. Implementation using SPL
PHP provides built-in interfaces SplSubject and SplObserver to implement this pattern easily.
The Subject
class User implements SplSubject {
public $email;
private $observers;
public function __construct($email) {
$this->email = $email;
$this->observers = new SplObjectStorage();
}
public function attach(SplObserver $observer) {
$this->observers->attach($observer);
}
public function detach(SplObserver $observer) {
$this->observers->detach($observer);
}
public function notify() {
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function changeEmail($newEmail) {
$this->email = $newEmail;
$this->notify();
}
}
The Observer
class LogHandler implements SplObserver {
public function update(SplSubject $subject) {
echo "LogHandler: User changed email to " . $subject->email . "\n";
}
}
Usage
$user = new User("john@example.com");
$logger = new LogHandler();
$user->attach($logger);
$user->changeEmail("john.doe@gmail.com");
// Outputs: LogHandler: User changed email to john.doe@gmail.com