SPL(標准PHP庫 - Standard PHP Library)是PHP5面向對象功能中重要的部分。原文解釋是這樣的“The Standard PHP Library (SPL) is a collection of interfaces and classes that are meant to solve common problems”。
SplSubject 和 SplObserver 接口
The SplSubject interface is used alongside SplObserver to implement the Observer Design Pattern.
觀察者模式是一種簡單的事件系統,包含了兩個或更多的互相交互的類。這一模式允許某個類觀察另一個類的狀態,當被觀察類的狀態發生變化時,這個模式會得到通知。被觀察的類叫subject,負責觀察的類叫做Observer 。PHP 提供的 SplSubject 和 SplObserver接口可用來表達這些內容。
SplSubject { /* 方法 */ abstract public void attach ( SplObserver $observer ) abstract public void detach ( SplObserver $observer ) abstract public void notify ( void ) }
SplObserver { /* 方法 */ abstract public void update ( SplSubject $subject ) }
這裡,splsubject類維護了一個特定狀態,當這個狀態發生變化時,他就會調用notify方法,所以之前使用attach注冊的splobserver實例的update就會被調用。這裡我們實現一個簡單地觀察者模式的例子
<?php /** * Subject,that who makes news */ class Newspaper implements \SplSubject{ private $name; private $observers = array(); private $content; public function __construct($name) { $this->name = $name; } //add observer public function attach(\SplObserver $observer) { $this->observers[] = $observer; } //remove observer public function detach(\SplObserver $observer) { $key = array_search($observer,$this->observers, true); if($key){ unset($this->observers[$key]); } } //set breakouts news public function breakOutNews($content) { $this->content = $content; $this->notify(); } public function getContent() { return $this->content." ({$this->name})"; } //notify observers(or some of them) public function notify() { foreach ($this->observers as $value) { $value->update($this); } } } /** * Observer,that who recieves news */ class Reader implements SplObserver{ private $name; public function __construct($name) { $this->name = $name; } public function update(\SplSubject $subject) { echo $this->name.' is reading breakout news <b>'.$subject->getContent().'</b><br>'; } } $newspaper = new Newspaper('Newyork Times'); $allen = new Reader('Allen'); $jim = new Reader('Jim'); $linda = new Reader('Linda'); //add reader $newspaper->attach($allen); $newspaper->attach($jim); $newspaper->attach($linda); //remove reader $newspaper->detach($linda); //set break outs $newspaper->breakOutNews('USA break down!'); //=====output====== //Allen is reading breakout news USA break down! (Newyork Times) //Jim is reading breakout news USA break down! (Newyork Times)