Home > Article > Backend Development > Implementation of PHP5+ standard function library observer_PHP tutorial
The implementation of PHP's observer design pattern is relatively simple, but the PHP5+ version already has standard library support, and we only need to simply inherit and implement it.
Observer: Implements the standard interface class library SplSubject. One registration method: attach, one deregistration method: detach. A notification method: nofity.
<?php class TSPLSubject implements SplSubject{ private $observers, $value; public function __construct(){ $this->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; } }
<?php class TSPLObserver implements SplObserver{ public function update(SplSubject $subject){ echo 'The new state of subject ' , nl2br("\r\n"); // echo 'The new state of subject '.$subject->getValue(); } }
<?php class TSPLObserver1 implements SplObserver{ public function update(SplSubject $subject){ echo 'The new state of subject one ' , nl2br("\r\n"); // echo 'The new state of subject '.$subject->getValue(); } }
<?php function __autoload($classname) { require_once ($classname . ".php"); } $subject = new TSPLSubject(); $subject->attach(new TSPLObserver()); $observer1 = new TSPLObserver1(); $subject->attach($observer1); //$subject->attach(new TSPLObserver2()); //$subject->detach($observer1); $subject->notify(); exit();
>php basic.php
The new state of subject
The new state of subject one