php design pattern observer pattern

Posted by aron on Sat, 04 Apr 2020 01:01:23 +0200

In web applications, generally, some small-scale data and business changes, and other relevant business data also need to change. In this case, observer pattern is very suitable.

Observer mode is usually implemented by using an interface called observer. If other classes want to introduce observers, they need to implement this interface

For example, there is a demand that if the exchange rate of products changes, the display information and price calculation of relevant pages of all products will also change

 1 interface Observer {
 2     function notify( $obj );
 3 }
 4 
 5 class ExchangeRate {
 6     static private $instance = NULL;
 7     private $observers = array();    
 8     private $exchange_rate;
 9 
10     private function __construct(){
11     }
12 
13     private function __clone(){
14     }
15 
16     public static function getInstance(){
17         if( self::$instance == NULL ) {
18             self::$instance = new ExchangeRate();
19         }
20         return self::$instance;
21     }
22 
23     public function getExchangeRate(){
24         return $this->exchange_rate;
25     }
26 
27     public function setExchangeRate( $new_rate ){
28         $this->exchange_rate = $new_rate;
29         //Exchange rate change, notify all observers
30         $this->notifyObservers();
31     }
32 
33     public function registerObservers( $obj ){
34         $this->observers[] = $obj;
35     }
36 
37     public function notifyObservers(){
38         foreach( $this->observers as $observer ) {
39             //Notify observer
40             $observer->notify( $this );
41         }
42     }
43 }
44 
45 class ProductItem implements Observer {
46     public function __construct(){
47         //Register as an observer of exchange rates
48         ExchangeRate::getInstance()->registerObservers( $this );
49     }
50     public function notify( $obj ){
51         if( $obj instanceof ExchangeRate ) {
52             echo "Please update the exchange rate of the product" . PHP_EOL;
53         }
54     }
55 }
56 
57 $p1 = new ProductItem();
58 $p2 = new ProductItem();
59     
60 ExchangeRate::getInstance()->setExchangeRate( 6.2 );

Topics: PHP