The last time you used pure PHP to implement an observer pattern (PHP watcher mode), now using PHP standard library SPL to implement the Observer mode at a time, the advantage is: randomly generate the observer you want to use!
Storage = new Splobjectstorage (); } function Attach (Splobserver $observer) {$this->storage->attach ($observer); } function Detach (Splobserver $observer) {$this->storage->detach ($observer); } function Notify () {foreach ($this->storage as $obs) {$obs->update ($this); }}/** * @author Jichao.wang * Execute login */function Handlelogin () {$ip = rand (1,100); Switch (rand (1, 3)) {Case 1: $this->setstatus (self::login_access, $IP); $ret = true; Break Case 2: $this->setstatus (Self::login_wrong_pass, $IP); $ret = false; Break Case 3: $this->setstatus (Self::login_user_unknown, $IP); $ret = false; Break }/** * Handle event */$this->notify (); return $ret; } /** * @param $status * @author Jichao.wang * Set Login Status */function SetStatus ($status, $ip) { $this->status = $status; $this->ip = $ip; }/** * @return mixed * @author Jichao.wang * Get login Status */function GetStatus () {R Eturn $this->status; }}/** * Only for the logged-in Viewer * class Loginobserver */abstract class Loginobserver implements Splobserver {private $login; function __construct (Login $login) {$this->login = $login; $login->attach ($this); }/** * External access point * @param splsubject $subject */function Update (Splsubject $subject) {if ($subj ECT = = = $this->login) {$this->doupdate ($subject); }} Abstract function DoUpdate (Login $login);} /** * Class emailobserver */class Emailobserver extends loginobserver{//different functions of the viewer implement different function functions DoUpdate (Login $l Ogin) {$status = $login->getstatus (); if ($status = = Login::login_access) {//$this->sendmail (' User ip: '. $observable->ip. ' Login successful! '); echo __class__. ' User ip: '. $login->ip. ' Login successful! ' ------------------'; if ($status = = Login::login_wrong_pass) {//$this->sendmail (' User ip: '. $observable->ip. ' Login failed, password wrong! ') ; echo __class__. ' User ip: '. $login->ip. ' Login failed, password wrong! '. ' ------------------'; if ($status = = Login::login_user_unknown) {//$this->sendmail (' User ip: '. $observable->ip. ' Login failed, no this user! ') ); echo __class__. ' User ip: '. $login->ip. ' Login failed, no this user! '. ' ------------------'; }}//Instantiate the login information $login = new login ();//implement e-mail observer New Emailobserver ($login);//Start landing $login->handlelogin ();