Simple example of observer pattern in php, php observer example
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 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 the notify method is called, the update methods of all SplObserver instances previously registered using the attach method will be called. The Demo is as follows:
Copy code 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);
http://www.bkjia.com/PHPjc/945719.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/945719.htmlTechArticleA simple example of the observer pattern in php, php observer example The observer pattern is one of the more common design patterns A pattern consists of two or more classes that interact with each other. This mode allows...
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