php observer mode is also very useful. Do you often use it?

Posted by phpwiz on Wed, 09 Feb 2022 19:02:04 +0100

Design pattern is the knowledge that every programmer must know and learn. Although it is not the foundation, you must understand it.

 

introduce

You may encounter it in programming. Sometimes the state change of an object will affect many kinds of behavior. Typically, in the purchase process, after successful purchase, it will affect inventory, sales volume, notify delivery, and some need to send text messages.

 

When the purchase behavior changes, other behaviors need to occur at the same time, but if they are written together, once the process changes, it will be more troublesome to change, and the coupling degree of writing these behaviors together is too high. The observer mode can solve this problem, so that the subject can notify the observer when changes occur by registering with the status subject, When the two are combined, the coupling degree is low. Implement an automatic update mechanism.

 

The above example does not seem to reflect the advantages of the observer model. For example, in a shopping website, the prices of various commodities are determined by the exchange rate. When the exchange rate changes, it is necessary to notify all product categories of price changes, but the number and number of product categories are uncertain, which makes it impossible for it to notify or let each product category actively query, Therefore, the observer mode must be used to implement this data binding at this time, which reminds me of the data binding mechanism in C #.

 

 

What is observer mode

Observer mode: when the state of an object changes, all objects that depend on it will be notified and updated automatically.

 

The core of Observer mode is the interface between subject and Observer. Subject contains a given state. The Observer "subscribes" to the topic and notifies the Observer of the current state of the topic.

 

It can be considered as a blog with many subscribers. It will regularly update a set of information for all kinds of users who subscribe to or read the blog regularly. Every time a blog changes (its status changes), all subscribers "will be notified".

 

The class diagram of observer mode is as follows (the drawing is not standard, it's good to explain the problem):

 

Observer mode usage scenario

The observer pattern is designed to let an object track a state and know when the state changes. Once the state changes, all subscription objects can be notified.

 

If you need to ensure the consistency of a state, but the given state may have multiple different views, the observer mode is very applicable and helpful. Using observer mode, consistency can be maintained and the number of objects that create a given state can be recorded at the same time.

 

Observer mode is intuitive. Why make multiple objects create or track a given state? It would be much more reasonable for an object to complete this work and then notify other objects that may use this state. Observer mode realizes a low coupling and non-invasive notification and update mechanism.

 

 

php implements observer mode

The three SPL interfaces / classes that can be used in the observer design pattern are as follows:

SplSubject
SplObserver
SplObjectStorage

 

3.1 the available methods of splsubject interface are as follows:

abstract public void attach ( SplObserver $observer )
abstract public void detach ( SplObserver $observer )
abstract public void notify ( void )

This interface specifies that the data type of $observer in the attach() and detach() method parameters must be a SplObserver object.

 

3.2 SplObserver

SplObserver Interface has a method update(),As follows:
abstract public void update( SplSubject $subject)

 

The update() method is crucial to the observer pattern because it gets the latest change in the Subject state and gives it to the observer instance.

 

3.3  SplObjectStorage

The SplObjectStorage class has no inherent relationship with the observer design pattern, but it can easily associate and disassociate an observer instance with a topic instance.

 

Although the SplObjectStorage class is generally described as a mapping from an object to data or a set of objects, I prefer to think of it as an array with built-in attach() and detach() methods.

 

This class provides a simple way to associate and disassociate an observer with a subject object that issues a state change notification.

 

3.4 implement observer mode

<?php

class Article implements SplSubject{
    public $has_update;
    public $has_comments;

    protected $observers = null;

    public function __construct(){
        $this->observers = new SplObjectStorage();

    }

    public function has_update($updated = false,$comments = true){
        $this->has_update = $updated;
        $this->has_comments = $comments;
        $this->notify();

    }
    //Bind observer
    public function attach(SplObserver $observer){
        $this->observers->attach($observer);

    }
    //Disarm observer
    public function detach(SplObserver $observer){
        $this->observers->detach($observer);

    }
    //Send notification
    public function notify(){
        $this->observers->rewind();
        //The current iteration item is invalid. You can also write foreach to terminate the loop
        // while($this->observers->valid()){
        //     $observer = $this->observers->current();
        //     $observer->update($this);
        //     $this->observers->next(); / / move the pointer back

        // }
        // 
        foreach($this->observers as $observer){
            $observer->update($this);

        }

    }

}


class ContentUpdateSubscribe implements SplObserver{
    public function update(SplSubject $subject){
        if($subject->has_update){
            echo "The articles you subscribe to have new news<br/>";

        }

    }

}


class CommentsUpdateSubscribe implements SplObserver{
    public function update(SplSubject $subject){
        if($subject->has_comments){
            echo "There are new comments on the articles you follow<br/>";

        }

    }

}


$article_1 = new Article();
$article_1->attach(new ContentUpdateSubscribe());
$article_1->attach(new CommentsUpdateSubscribe());
$article_1->has_update(true,true);

 

The operation results are as follows

Topics: PHP