Home > Backend Development > PHP Tutorial > Simple example of observer pattern in php_PHP tutorial

Simple example of observer pattern in php_PHP tutorial

WBOY
Release: 2016-07-13 10:01:41
Original
882 people have browsed it

A simple example of the observer pattern in php

This article mainly introduces a simple example of the observer pattern in php. The observer pattern is a common pattern in design patterns. , including two or more classes that interact with each other. This article directly gives the implementation code. Friends who need it can refer to it

The observer pattern is a common pattern in design patterns, including two or more classes that interact with each other. This mode allows a class to observe the state of another class. When the state of the observed class changes, the observer will be notified and update the corresponding state.

php's SPL standard class library provides the SplSubject and SplObserver interfaces for implementation. The observed class is called subject, and the class responsible for observation is called observer. This mode is that the SplSubject class maintains a specific state,

When this status changes, it will call the notify method. When calling the notify method, the update methods of all SplObserver instances previously registered using the attach method will be called. The Demo is as follows:

The code is as follows:


class DemoSubject 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]);
}
}

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 DemoObserver implements SplObserver{
public function update(SplSubject $subject){
echo 'The new value is '. $subject->getValue();
}
}

$subject = new DemoSubject();
$observer = new DemoObserver();
$subject->attach($observer);
$subject->setValue(5);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/971940.htmlTechArticleA simple example of the observer pattern in php. This article mainly introduces a simple example of the observer pattern in php. Observation The operator pattern is a common pattern in design patterns, consisting of two or more...
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