Php design pattern observer pattern, design pattern observer
The core of the observer mode is to separate the customer element (observer) from a central class (subject. When the subject knows that an event occurs, the observer must be notified. At the same time, we do not want to hard encode the relationship between the subject and the observer. To achieve this goal, we can allow the observer to register on the subject.
The observer mode implements a low-coupling, non-intrusive notification and update mechanism.
Scenario: when an event occurs, perform a series of update operations.
EventGenerator.php
<? Phpnamespace Baobab;/*** Class EventGenerator base class, event producer */abstract Class EventGenerator {// The observer is invisible to the event producer, the event owner does not care which observers are interested in the event private $ observers = array ();/*** add Observer */function addObserver (observer $ Observer) {$ this-> observers [] = $ observer;}/*** notify the observer one by one to perform update operations */function Y () {foreach ($ this-> observers as $ observer) {$ observer-> update ();}}}
Observer.php
<? Phpnamespace Baobab;/*** Class Observer, the observed object is the event sender * @ package Baobab */interface Observer {/*** @ param null $ event_info event information * indicates the update operation after the event */function update ($ event_info = null );}
Index. php
Class Event extends \ Baobab \ EventGenerator {/*** triggers a new Event */function trigger () {echo 'event occurred '; $ this-> Policy ();}} /*** Observer 1 */class Observer1 implements \ Baobab \ Observer {function Update ($ event_info = null) {echo 'Update operation code 1 ';}}
/**
* Observer 2
*/Class Observer2 implements \ Baobab \ Observer {function Update ($ event_info = null) {echo 'Update operation code 2'; }}$ event = new Event (); $ event-> addObserver (new Observer1 (); $ event-> addObserver (new Observer2 (); $ event-> trigger ();