php -- observer mode

Posted by kester on Tue, 17 Dec 2019 20:31:15 +0100

Observer mode

When an object or event changes, other object instances or events need to be changed accordingly or one to many relationships with corresponding actions can be applied.

For example: after the order status changes (payment is completed), a series of corresponding operations such as SMS notification and public number push are required. The order class can be regarded as an observer, SMS notification class, public account notification, app push and other related notification classes as observers.

Specific implementation and calling steps:

Respectively implement the SplSubject and SplObserver classes, and instantiate the SplObjectStorage class in the SplSubject implementation class to store the objects

Add the observer object to the observed object for storage

Call the notification method after the object changes, and notify the observer object one by one for relevant operations

Benefits:

Avoid countless judgment operations, resulting in code bloated and unsightly

Reduce coupling

<?php
header("Content-Type: text/html;charset=utf-8");
class test implements SplSubject{//Observed class

    public $_observer;
    public $num;
    public $ad;
    function __construct()
    {
        $this->_observer = new SplObjectStorage();
    }

    public function run(){
        $this->notify();
        print_r($this);
    }

    public function attach(SplObserver $observer)
    {
        // TODO: Add observer object
        $this->_observer->attach($observer);
    }

    public function detach(SplObserver $observer)
    {
        // TODO: Implement detach() method.
        $this->_observer->detach($observer);
    }

    public function notify()
    {
        // TODO: Implement notify() method.
        foreach ($this->_observer as $obj){
            $obj->update($this);
        }
    }
}

class checkNum implements SplObserver{
    public function update(SplSubject $subject)
    {
        // TODO: Update according to notification
        $subject->num = "Inspection times";
    }
}

class checkAd implements SplObserver{
    public function update(SplSubject $subject)
    {
        // TODO: Update according to notification
        $subject->ad = "Check advertising";
    }

}

$test = new test();
$test->attach(new checkNum());
$test->attach(new checkAd());
$test->run();
Observer mode

If there is any mistake, please point out

Topics: PHP