<?php
class Subject implements SplSubject {
private $observers = [];
private $state;
public function attach(SplObserver $observer) {
$this->observers[] = $observer;
}
public function detach(SplObserver $observer) {
foreach ($this->observers as $key => $obs) {
if ($obs === $observer) {
unset($this->observers[$key]);
}
}
}
public function notify() {
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function setState($state) {
$this->state = $state;
$this->notify();
}
public function getState() {
return $this->state;
}
}
class Observer implements SplObserver {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function update(SplSubject $subject) {
echo "观察者==》{$this->name} 开始执行事件: " . $subject->getState() . "\n";
}
}
// 创建主题
$subject = new Subject();
// 创建观察者
$observer1 = new Observer("观察者 1");
$observer2 = new Observer("观察者 2");
// 将观察者添加到主题
$subject->attach($observer1);
$subject->attach($observer2);
// 改变状态
$subject->setState("事件");