PHP5.0以上版本内置了观察者模式的实现。
观察者模式应用的场景:
1,比如新增加用户的时候,需要给用户发送邮件和短信进行通知。我们的主程序就是完成用户的增其,其他方法对进行发短信和通知。
2,具体的代码使用如下
email; } public function getName() { return $this->name; } public function getSex() { return $this->sex; } public function setEmail($email) { $this->email = $email; } public function setName($name) { $this->name = $name; } public function setSex($sex) { $this->sex = $sex; } public function __construct($name,$email,$sex) { $this->name=$name; $this->email=$email; $this->sex=$sex; $this->observs=new SplObjectStorage(); } public function attach(SplObserver $observer) { $this->observs->attach($observer); } public function detach(SplObserver $observer) { $this->observs->detach($observer); } public function notify() { foreach($this->observs as $obs) { $obs->update($this); } } public function crete() { echo "新增了一个名为{ $this->name}的用户"; $this->notify(); } public function resetpwd() { echo "用户{ $this->name}重置了密码"; $this->notify(); }}//观察者class sendmsg implements SplObserver{ public function update(SplSubject $subject) { echo "我要发短信了,给用户{ $subject->getName()}"; }}class sendemail implements SplObserver{ public function update(SplSubject $subject) { echo "我给{ $subject->getName()}发邮件了"; }}//测试脚本$user=new User("小花猫","小花猫@小花猫","猫猫");$sendemail=new sendemail();$sendmsg=new sendmsg();$user->attach($sendemail);//注册发邮件的事件$user->attach($sendmsg);//发留言信息$user->crete();echo "我要重置密码 ";$user->detach($sendmsg);$user->resetpwd();
其中user方法实现了spl的接口splsubject,观察者实现了splObserver接口。对于spl是个什么东西,请参考 今天发现php.net改版了!现在一些东西在上边都很好找。