Simple example of observer pattern in PHP, PHP watcher Instance
The Observer pattern is one of the more common patterns in design patterns, with two or more classes interacting with one another. This pattern allows a class to observe the state of another class, and when the state of the observed class changes, the observer will be notified to 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 that is responsible for the observation is called Observer. This pattern is a splsubject class that maintains a specific state,
When this state changes, it calls the Notify method. When the Notify method is called, all the update methods of the Splobserver instance that were previously registered using the Attach method are called, with the following demo:
Copy CodeThe 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.html www.bkjia.com true http://www.bkjia.com/PHPjc/945719.html techarticle A simple example of observer patterns in PHP, the PHP Watcher Instance Observer pattern is a more common pattern in design patterns, containing two or more classes interacting with each other. This mode allows ...