Home >Backend Development >PHP Tutorial >Implementation code of PHP observer pattern_PHP tutorial
The code is as follows:
//Instantiate, generate an observer object
public function __construct(){
$this->_observers = new SplObjectStorage();
}
// Add observer object
public function attach(SplObserver $observer){
$this->_observers->attach($observer);
}
//Delete the observer object
public function detach(SplObserver $observer){
$this->_observers->detach($observer);
}
//Notification message
public function notify(){
foreach($this->_observers as $observer){
$observer->showMessage($this);
}
}
//Normal method: Set value
public function setName($name){
$this->_name = $name;
$this->notify();
}
//Ordinary method: Get value
public function getName(){
return $this->_name;
}
//Normal method: set 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{
//Show message prompt
$user = $obj->getName();
if($user==='admin'){
Echo 'Hello,', $ user, 'Welcome to enter the management background & lt; br/& gt;';
} else {
echo "Hello, '$ user' you have been added to User list
";
}
}
//This is an abstract method that inherits from the parent class
public function update(SplSubject $subject) {}
//Show personal age
echo "<script>alert('$name's age is: $age')</script>" ;
}
}
$subject = new Observed(); //Generate an observed object
$subject->attach($observer) ;//Pass the observer into the observed
$subject->setName('Zhang San'); //Call the setName method
/*
* It will be called through the setName above $this->notify();
* By calling $this->notify(), the $observer->showMessage($this) method will be called,
* which is the showMessage of each observer object ($obj) method;
*/
$subject->setName('admin');
$subject->setAge(24);
http://www.bkjia.com/PHPjc/326995.html