An introduction to the observer pattern for the PHP design pattern

  • 2020-05-12 02:24:25
  • OfStack

introduce
The observer pattern defines the 1-to-multiple dependencies of an object so that when an object changes state, all its dependencies are notified and automatically updated!
Design principles
In observer mode, what changes is the state of the subject and the number of observers. With this pattern, you can change objects that depend on the topic state without changing the topic. Identify the aspects of the program that will change, and then separate them from the fixed aspects!
Both the subject and the observer use interfaces: the observer registers with the subject using the subject's interface, and the subject notifies the observer using the observer interface. This allows the two to function properly while at the same time having the advantage of loose coupling! Programming for interfaces, not implementations!
.
The observer pattern USES "composition" to group many observers into a topic. This relationship between objects (observer -- subject) is not created by inheritance, but by composition at runtime. Use more combinations, less inheritance!
code
 
<?php 
/** 
*  Observer mode  
* @author: Mac 
* @date: 2012/02/22 
*/ 
class Paper{ /*  The theme  */ 
private $_observers = array(); 
public function register($sub){ /*  Registered observer  */ 
$this->_observers[] = $sub; 
} 
public function trigger(){ /*  The external system 1 access  */ 
if(!empty($this->_observers)){ 
foreach($this->_observers as $observer){ 
$observer->update(); 
} 
} 
} 
} 
/** 
*  The interface to be implemented by the observer  
*/ 
interface Observerable{ 
public function update(); 
} 
class Subscriber implements Observerable{ 
public function update(){ 
echo "Callback\n"; 
} 
} 
// Here is the test code  
? 
/*  test  */ 
$paper = new Paper(); 
$paper->register(new Subscriber()); 
//$paper->register(new Subscriber1()); 
//$paper->register(new Subscriber2()); 
$paper->trigger(); 


conclusion

When a new object is to be filled in, simply register it in the subject (also known as an observer) (there are many ways to register it, but you can also register it at construction time, or in an interface that the framework accesses), and then implement the code directly into the interface of the new object. This reduces the coupling between the topic object and the observer object.

Good design patterns don't go directly into your code, they go into your brain.

Related articles: