PHP 5 + standard function library observer implementation
The observer design mode of PHP is relatively simple to implement, but the PHP5 + version already has support for standard library libraries. We only need to simply inherit and implement it.
Observer: implements the standard interface class library SplSubject. One registration method is attach and the other is detach. One notification method: nofity.
observers =array(); } public function attach(SplObserver $observer){$this->observers[] = $observer; } public function detach(SplObserver $observer){if($idx = array_search($observer, $this->observers,true)) {unset($this->observers[$idx]);} } /** * * Notify observers one by one (main entry) * * @param none * @return none */ public function notify(){foreach($this->observers as $observer){$observer->update($this);} } public function setValue($value){$this->value = $value;//$this->notify(); } public function getValue(){ return $this->value; }}
Observer: implements the standard interface class library SplObserver. An update method.
getValue(); }}
getValue(); }}
Test Call (in the same directory ):
attach(new TSPLObserver());$observer1 = new TSPLObserver1();$subject->attach($observer1);//$subject->attach(new TSPLObserver2());//$subject->detach($observer1);$subject->notify();exit();
Output:
> Php basic. php
The new state of subject
The new state of subject one