<?php /** * 【观察者模式】 * PHP5中提供了 观察者(observer) 和 被观察者(subject) 的接口 * 在手册搜索:SplSubject (PHP 5 >= 5.1.0) * * SplSubject { * abstract public void attach ( SplObserver $observer ) * abstract public void detach ( SplObserver $observer ) * abstract public void notify ( void ) * } * */ header("Content-type: text/html; charset=utf-8"); /*根据登录次数和爱好,进行观察.定义user类,实现SplSubject接口 */ class User implements SplSubject{ public $lognum; //登录次数 public $hobby; //爱好 protected $observers; //用来储存对象 public function __construct($hobby){ $this->lognum = rand(1,10); //登录次数:随机数 $this->hobby = $hobby; //爱好:参数传递 $this->observers = new SplObjectStorage(); } //登录操作 public function login(){ //操作session... 代码忽略 //登录后,触发notify $this->notify(); } //观察 public function attach(SPLObserver $observer){ $this->observers->attach($observer); } //取消观察 public function detach(SPLObserver $observer){ $this->observers->detach($observer); } //通知 public function notify(){ $this->observers->rewind(); //不断循环获取储存的对象 while($this->observers->valid()){ $observer = $this->observers->current(); $observer->update($this); $this->observers->next(); } } } /*假如现在有个“安全模块” security 要来观察 */ class security implements SPLObserver{ public function update(SplSubject $subject){ if($subject->lognum < 3){ echo '这是第'.$subject->lognum.'次安全登录<br>'; }else{ echo '这是第'.$subject->lognum.'次登录,出现异常。<br>'; } } } /*再假如现在有个“广告模块” ad 要来观察 */ class ad implements SPLObserver{ public function update(SplSubject $subject){ if($subject->hobby == 'sports'){ echo '开运动会<br>'; }else{ echo '哈哈哈哈哈哈<br>'; } } } /*实施观察*/ //实例化User $user = new User('sports'); //实施“安全模块”的观察 $user->attach(new security()); //实施“广告模块”的观察 $user->attach(new ad()); //执行登录操作 $user->login();