// 實作功能:登入時 通知安全模組 與 廣告模組
// 預先定義介面:SplObserver觀察者與SplSubject被觀察者
class User implements SplSubject
#{
protected $login_num;
protected $hobby;
protected $_subject;
public function __construct($login_num, $hobby)
{
$this->login_num = $login_num;
$this->hobby = $hobby;
// 儲存觀察者對象
$this->_subject = new SplObjectStorage();
}
public function __get($name)
#{
// TODO: Implement __get() method.
return $this->$name;
}
#public function login()
{
// 操作...
$this->notify();
}
// SplSubject 介面
#public function attach(SplObserver $observer)
{
// TODO: Implement attach() method.
$this->_subject->attach($ observer);
}
public function detach(SplObserver $observer)
{
// TODO: Implement detach() method.
$this->_subject->detach($observer);
#}
public function notify()
##{#/ / TODO: Implement notify() method.foreach ($this->_subject as $observer) {$observer->update($this);}}}// 觀察者再此觀察使用者登入// 安全性檢查class safe implements SplObserver{public function update(SplSubject $subject){// TODO: Implement update() method. #if ($subject->login_num > 10) {echo '今日登陸次數超過10次,可能有密碼外洩問題,請重設密碼! ';} else {echo '今日第' . $subject->login_num . '次安全登入! ';}}}// 廣告推廣class ad implements SplObserver{ public function update(SplSubject $subject){// TODO: Implement update() method.if ($subject-> hobby == 'sports') {echo '這是體育廣告! ';} else {echo '隨機廣告! ';}}}$hobby = ['sports', 'eat', 'drink', 'sleep', ' play'];$user = new User(random_int(1, 20), $hobby[shuffle($hobby)]);$user->attach(new safe( ));$user->attach(new ad());#// 使用者登入時觸發一些列觀察者$user->login ();
#