The Observer pattern I understand is that when we trigger an event, we want to tell the action to the object I want to tell, and let them all do it, just to bind them to this event.
1. Define a base class (for adding observers also is the object I want to notify, as well as notifying the observer)
eventgenerator.php
!--? php abstract class eventgenerator { //Store watcher because there can be more than one object to notify, so it's an array private $observers = array (); //Add observer, which is the object I want to notify Public function addobserver ( $observer ) { $this ->observers[] = $observer ; //Notify Observer public function notify () { span>//remove all objects to perform operation foreach ( $this ->observers as $observer ) {///Here I write an update method, which requires that all of my notification objects must have an update operation, so I'll define an excuse for all observers to enforce this method $ob Server ->update (); }}} ?
Define the interface file so that all observers implement the Update method observer.php
interfaceObserver{functionupdate();}?>
Defines a file that implements the Observer pattern event.php
Header' Content-type:text/html;charset=utf-8 ');d Efine (' BASEDIR ', __dir___);require' config.php '; Spl_autoload_register (' Config::autoload ');//Define event class inheritance base class classEventextendseventgenerator{notify all observers when this event is triggered Public functiontrigger() {Echo' I'm going to start the update!
\ n ';//base class notification method$this->notify (); }}//Add Observer 1 classObserver1implementsObserver{ Public functionupdate() {Echo' I am observer 1, I have received your notice! ' I'm going to do what I have to do!
\ n '; }}//Add Observer 2 classObserver2implementsObserver{ Public functionupdate() {Echo' I am observer 2, I have received your notice! ' I'm going to do what I have to do!
\ n '; }}//The test will start next! $event=NewEvent ();//Add observer to this event$event->addobserver (NewObserver1);$event->addobserver (NewOBSERVER2);//Perform trigger operation$event->trigger ();//This time it will be displayed! //I want to start the update Ah! //I am observer 1, I have received your notice! I'm going to do what I have to do! //I am observer 2, I have received your notice! I'm going to do what I have to do! ?>
'). addclass (' pre-numbering '). Hide (); $ (this). addclass (' has-numbering '). Parent (). append ($numbering); for (i = 1; i <= lines; i++) {$numbering. Append ($ ('
'). Text (i)); }; $numbering. FadeIn (1700); }); });
The above describes the PHP observer pattern, including the viewer mode, PHP content, I hope that the PHP tutorial interested in a friend helpful.