Getting started with php observer pattern example

WBOY
Release: 2016-07-25 08:52:08
Original
865 people have browsed it
  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);
复制代码


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!