Implementation code for the PHP Observer pattern

  • 2020-06-03 06:01:32
  • OfStack

The code is as follows:


// The observed abstract class 
class Observed implements SplSubject{
    protected $_name;
    protected $_observers;
    // instantiation , generate 1 Five observer objects 
    public function __construct(){
        $this->_observers = new SplObjectStorage();
    }
    //  Add observer object 
    public function attach(SplObserver $observer){
        $this->_observers->attach($observer);
    }
    // Delete viewer objects 
    public function detach(SplObserver $observer){
        $this->_observers->detach($observer);
    }
    // Notification message 
    public function notify(){
        foreach($this->_observers as $observer){
            $observer->showMessage($this);
        }
    }
    // Common methods :  Set the value 
    public function setName($name){
        $this->_name = $name;
        $this->notify();
    }
    // Common methods :  Get the value 
    public function getName(){
        return $this->_name;
    }
    // Common methods : 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 prompt 
    public function showMessage(SplSubject $obj){
        $user = $obj->getName();
        if($user==='admin'){
            echo ' How do you do , ',$user,' Welcome to the management background <br/>';
        }else{
            echo " hello , '$user'  You have been added to the user list <br/>";
        }
    }
    // This is an abstract method that inherits the parent class 
    public function update(SplSubject $subject) {}
    // Show personal age 
    public function showAge($name,$age){
        echo "<script>alert('$name  The age is : $age')</script>";
    }
}
$subject = new Observed();  // generate 1 Three observed objects 
$observer = new Observer(); // generate 1 Five observer objects 
$subject->attach($observer);// To impart the observer to the observed 
$subject->setName(' zhang 3'); // call  setName  methods 
/*
 *  Through the  setName  Is called   $this->notify();
*  By calling the   $this->notify() Is called  $observer->showMessage($this) methods ,
*  For each observer object  showMessage($obj) methods ;
*/
$subject->setName('admin');
$subject->setAge(24);


Related articles: