The php Standard Library spl is used to implement the observer mode. The last time the pure php is used to implement the observer mode (php observer mode), the following advantages apply to the php Standard Library spl: generate the observer you want to use at will!
Storage = new SplObjectStorage ();} function attach (SplObserver $ observer) {$ this-> storage-> attach ($ observer);} function detach (SplObserver $ observer) {$ this-> storage-> detach ($ observer);} function Policy () {foreach ($ this-> storage as $ obs) {$ obs-> update ($ this) ;}}/*** @ author jichao. wang * perform logon */function handleLogin () {$ ip = rand (1,100); switch (rand (1, 3) {case 1: $ this-> setStatus (sel F: 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-> handle Y (); 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 () {return $ this-> status ;}} /*** only for the logon observer * Class LoginObserver */abstract class LoginObserver implements SplObserver {private $ login; function _ construct (Login $ login) {$ this-> login = $ login; $ login-> attach ($ this );} /*** unified access point * @ param SplSubject $ subject */function update (SplSubject $ subject) {if ($ subject ===$ This-> login) {$ this-> doUpdate ($ subject) ;}} abstract function doUpdate (Login $ login );} /*** Class EmailObserver */class EmailObserver extends LoginObserver {// different function observers implement different function doUpdate (Login $ login) {$ status = $ login-> getStatus (); if ($ status = Login: LOGIN_ACCESS) {// $ this-> sendMail ('User ip :'. $ observable-> ip. 'login successful! '); Echo _ CLASS _.' user ip address: '. $ login-> ip.' login successful! '. '----------------';} If ($ status = Login: LOGIN_WRONG_PASS) {// $ this-> sendMail ('User ip :'. $ observable-> ip. 'login failed, incorrect password! '); Echo _ CLASS _.' user ip address: '. $ login-> ip.' login failed, incorrect password! '. '----------------';} If ($ status = Login: LOGIN_USER_UNKNOWN) {// $ this-> sendMail ('User ip :'. $ observable-> ip. 'login failed. This user does not exist! '); Echo _ CLASS _.' user ip address: '. $ login-> ip.' login failed. This user does not exist! '. '----------------' ;}}// Instantiate the login information $ Login = new login (); // implement the Mail observer new EmailObserver ($ login ); // start logging on to $ login-> handleLogin ();