1: Observer mode. When the state of an object changes, all dependent objects are notified and updated automatically. 2: Scenario: After an event occurs, a series of updates are performed. The traditional way of programming is to add the processing logic directly after the event code. As the updated logic grows, the code becomes difficult to maintain. This approach is coupled and intrusive, and adding new logic requires modifying the body code of the event. 3: Observer mode implements a low coupling, non-intrusive notification and update mechanism.

Let’s take specific scenarios as examples: for example, after users register successfully, they can send points to users, send coupons and so on.

We define an observer interface and define the specific methods that the observer needs to execute. Of course, the name and number of methods can be customized

interface Observer
{
    public function update();
}
Copy the code

Define one more event class: define methods to add observers and broadcast notifications

/** ** Class */ abstract Class EventGenerator {private $ObServers = []; Public function add(ObServer $ObServer) {$this->ObServers[] = $ObServer; } public function notify() {foreach ($this->ObServers as $ObServer) {$ObServer->update(); }}}Copy the code

Define an observer concrete class

*/ class Point implements ObServer {public function update() {echo "implements ObServer "; } /** * implements ObServer {public function update() {echo "implements ObServer "; }}Copy the code

Define concrete event classes

/** * public function trigger(); /** * Public function trigger() $this->notify(); }}Copy the code

test

$event = new UserRegisteredEvent(); $event->add(new Point()); $event->add(new Coupon()); $event->trigger();Copy the code

Reference: www.cnblogs.com/chrdai/p/11…

www.cnblogs.com/onephp/p/61…