PHP observer mode principle and simple implementation method example, php observer principle example
This article describes the principles and simple implementation of the PHP observer mode. We will share this with you for your reference. The details are as follows:
When the State of an object changes, it will affect the changes of other objects. In this case, the observer mode can be used. In an application such as wordpress, it allows external developers to develop plug-ins, such as user-authorized blog statistics plug-ins and point plug-ins. In this case, you can use the observer mode to register these plug-ins first, after a user publishes a blog post, the corresponding plug-in update is automatically notified.
The observer mode conforms to the interface isolation principle and achieves loose coupling between objects.
Observer mode UML diagram:
SplSubject and SqlOberver interfaces have been provided in php SPL.
interface SplSubject{ function attach(SplObserver $observer); function detach(SplObserver $observer); function notify();}interface SqlObserver{ function update(SplSubject $subject);}
The following is an example.
Class Subject implements SplSubject {private $ observers; public function attach (SplObserver $ observer) {if (! In_array ($ observer, $ this-> observers) {$ this-> observers [] = $ observer ;}} public function detach (SplObserver $ observer) {if (false! = ($ Index = array_search ($ observer, $ this-> observers) {unset ($ this-> observers [$ index]);} public function post () {// post related code $ this-> Policy ();} private function using Y () {foreach ($ this-> observers as $ observer) {$ observer-> update ($ this) ;}} public function setCount ($ count) {echo "data volume plus ". $ count;} public function setIntegral ($ integral) {echo "add points ". $ integral ;}} class Observer1 implements SplObserver {public function update ($ subject) {$ subject-> setCount (1 );}} class Observer2 implements SplObserver {public function update ($ subject) {$ subject-> setIntegral (10) ;}} class Client {public function test () {$ subject = new Subject (); $ subject-> attach (new Observer1 (); $ subject-> attach (new Observer2 ()); $ subject-> post (); // output: data volume plus 1 point plus 10 }}