In fact, the Observer Mode is a mode that is easier to understand. it is an event system, which means that this mode allows a class to observe the status of another class, when the status of the observed class changes, the observed class can receive notifications and make corresponding actions. For example, when I press the keyboard, the system will receive a notification and respond accordingly.
In fact, the Observer Mode is a mode that is easier to understand. it is an event system, which means that this mode allows a class to observe the status of another class, when the status of the observed class changes, the observed class can receive notifications and make corresponding actions. For example, when I press the keyboard, the system will receive a notification and respond accordingly.
For PHP, PHP provides two built-in interfaces for external application areas to implement this mode.
SplSubject interface, which represents the object to be observed,
Its structure:
SplObserver interface, which represents the object that acts as the Observer,
Its structure:
This mode is implemented in this way. SplSubject maintains a specific state. when this state changes, it uses notify Y () to notify all splobservers registered to SplSubject with attach, and call the corresponding update method.
Simple example:
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]); } } 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; } } class observer implements SplObserver{ public function update(SplSubject $subject){ echo 'The new state of subject'.$subject->getValue(); } } $subject = new subject(); $observer = new observer(); $subject->attach($observer); $subject->setValue(5);