Home >Backend Development >PHP Tutorial >Implementation code of PHP observer pattern_PHP tutorial

Implementation code of PHP observer pattern_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:11:01906browse

The code is as follows:

Copy the codeThe code is as follows:

//Inspected or abstract class
class Observed implements SplSubject{
protected $_name;
protected $_observers;

//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

public function showMessage(SplSubject $obj){

$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

public function showAge($name,$age){

echo "<script>alert('$name's age is: $age')</script>" ;
}
}

$subject = new Observed(); //Generate an observed object

$observer = new Observer(); //Generate an observer 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

truehttp: //www.bkjia.com/PHPjc/326995.htmlTechArticleThe code is as follows: Copy the code The code is as follows: //Observed abstract class class Observed implements SplSubject{ protected $ _name; protected $_observers; //Instantiate, generate an observer...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn