PHP observer mode implementation code. The code is as follows: Copy the code as follows: the observed abstract class classObservedimplementsSplSubject {protected $ _ name; protected $ _ observers; instantiate and generate an Observer
The code is as follows:
The code is as follows:
// The observed abstract class
Class Observed implements SplSubject {
Protected $ _ name;
Protected $ _ observers;
// Instantiate to generate an observer object
Public function _ construct (){
$ This-> _ observers = new SplObjectStorage ();
}
// Add an observer object
Public function attach (SplObserver $ observer ){
$ This-> _ observers-> attach ($ observer );
}
// Delete the viewer object
Public function detach (SplObserver $ observer ){
$ This-> _ observers-> detach ($ observer );
}
// Notification message
Public function required Y (){
Foreach ($ this-> _ observers as $ observer ){
$ Observer-> showMessage ($ this );
}
}
// Normal method: set the value
Public function setName ($ name ){
$ This-> _ name = $ name;
$ This-> Policy ();
}
// Normal method: get the value
Public function getName (){
Return $ this-> _ name;
}
// Normal method: set the age
Public function setAge ($ age ){
$ This-> age = $ age;
Foreach ($ this-> _ observers as $ observer ){
$ Observer-> showAge ($ this-> _ name, $ this-> age );
}
}
}
// Observer abstract class
Class Observer implements SplObserver {
// Display message prompts
Public function showMessage (SplSubject $ obj ){
$ User = $ obj-> getName ();
If ($ user = 'admin '){
Echo 'hello, ', $ user,' Welcome to the management background
';
} Else {
Echo "hi, '$ user' you have been added to the user list
";
}
}
// This is an abstract method that inherits the parent class
Public function update (SplSubject $ subject ){}
// Display the personal Age
Public function showAge ($ name, $ age ){
Echo "script" alert ('$ name is: $ age') script ";
}
}
$ Subject = new Observed (); // generates an object to be Observed.
$ Observer = new Observer (); // generates an observer object
$ Subject-> attach ($ observer); // transmits the observer to the observed object.
$ Subject-> setName ('Zhang San'); // call the setName method
/*
* The following setName will call $ this-> Policy ();
* By calling $ this-> notify (), the $ observer-> showMessage ($ this) method is called,
* This is the showMessage ($ obj) method of each observer object;
*/
$ Subject-> setName ('admin ');
$ Subject-> setAge (24 );
The Observer code is as follows: // The class Observed implements SplSubject {protected $ _ name; protected $ _ observers; // instantiate the object to generate an observer...