Home  >  Article  >  Backend Development  >  Getting started with php observer pattern example

Getting started with php observer pattern example

WBOY
WBOYOriginal
2016-07-25 08:52:08866browse
  1. class DemoSubject implements SplSubject{
  2.     private $observers, $value;
  3.     public function __construct(){
  4.         $this->observers = array();
  5.     }
  6.     public function attach(SplObserver $observer){
  7.         $this->observers[] = $observer;
  8.     }
  9.     public function detach(SplObserver $observer){
  10.         if($idx = array_search($observer, $this->observers, true)){
  11.             unset($this->observers[$idx]);
  12.         }
  13.     }
  14.     public function notify(){
  15.         foreach($this->observers as $observer){
  16.             $observer->update($this);
  17.         }
  18.     }
  19.     public function setValue($value){
  20.         $this->value = $value;
  21.         $this->notify();
  22.     }
  23.     public function getValue(){
  24.         return $this->value;
  25.     }
  26. }
  27. class DemoObserver implements SplObserver{
  28.     public function update(SplSubject $subject){
  29.         echo 'The new value is '. $subject->getValue();
  30.     }
  31. }
  32. $subject = new DemoSubject();
  33. $observer = new DemoObserver();
  34. $subject->attach($observer);
  35. $subject->setValue(5);
复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn