Parsing PHP observer mode observer

  • Observer mode structure diagram
  • concept
  • Code example

Observer mode structure diagram


An “actor” (observed), a group of “audience” (observers), a “camera” (recording container)

[main roles in observer mode]

1. Abstract subject role: the subject role saves all references to observer objects in a set, and each subject can have any number of observers. Abstract topics provide interfaces for adding and deleting observer objects.

2. Abstract observer role: define an interface for all concrete observers to update themselves when the observed topic changes.

3. Concretesubject role: store the relevant state to the specific observer object. When the internal state of the specific subject changes, send a notice to all registered observers. Specific topic roles are usually implemented with a specific subclass.

4. Concreteobserver role: store a specific subject object, store the relevant state, and implement the update interface required by the abstract observer role to make its own state consistent with the state of the subject.

[usage scenario]

Suppose the project manager asked us to write a login interface, and it was finished

The next day, let’s add the statistics of login times, and then add the code later. On the third day, let’s judge the login area, and then add the code later. On the fourth day, let’s push the activity after the user logs in, and then add the code later. On the n day, this interface is so messy that no one wants to maintain it

We need to keep the project high cohesion and low coupling, so we can use the observer mode (not necessary, depending on the requirements)

[observer mode and other modes]

1. [mediator mode]: by encapsulating complex update semantics, changemanager acts as a mediator between the target and the observer.
2. [singleton mode] (singleton mode): changemanager can use singleton mode to ensure that it is unique and globally accessible.

Code example

Interface example

//Topic interface
interface Subject{
    public function register(Observer $observer);
    public function notify();
//Observer interface
interface Observer{
    public function watch();

Subject is the observed, observer is the audience, that is, the observer

Observed person

//Observed person
class Action implements Subject{
     public $_observers=array();
     public function register(Observer $observer){
     public function notify(){
         foreach ($this->_observers as $observer) {

Action implements the observed interface. Now it is the observed. Define another one$_ Observers array, which is the container for recording audiences.

First, implement the register method, use it to pass in an observer, then insert it into the array, and then implement the notify () method. It will traverse the container array and execute each observer’s watch () method.


class Cat implements Observer{
     public function watch(){
         echo "Cat watches TV<hr/>";
 class Dog implements Observer{
     public function watch(){
         echo "Dog watches TV<hr/>";
 class People implements Observer{
     public function watch(){
         echo "People watches TV<hr/>";

Three observers are defined here, all of which implement the observer interface. The previous subject will call each observer’s watch () method circularly, so we need to implement each observer’s watch () method.


//Application examples
$action=new Action();
$action->register(new Cat());
$action->register(new People());
$action->register(new Dog());

First, new the observed object, execute its register () method, put each observer into the container array, and finally execute the notify () method to notify all observers to execute their own methods.

Observer mode native to PHP

PHP has its own observer mode

  • Splsubject interface – observed
  • Observer interface – observer
  • Splobjectstorage object – container

First, we have a user login class

class user{

  public function login()
      Echo 'login completed'

Let him implement the splsubject interface and become an observer.

  • First, in the constructor, let him new splobjectstorag() object and assign it to the attribute for later calling
  • Implement the attach () method to register observers
  • Implement the detach () method to delete the observer
  • Implement the notify () method to traverse the container and call the update method of each observer (it must be update)
  • The rewind method resets the container pointer to the beginning. The valid method detects whether the container traverses and returns Booleans. The current method obtains the current observer, and the next method moves the pointer back one bit
  • Modify the login () method, and call notify () inside to notify the observer that the event is completed
class user implements splsubject{

    protected $observer = null;

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

    public function login()
        Echo 'login completed';

    public function attach(SplObserver $observer)

    public function detach(SplObserver $observer)

    public function notify()
        while ($this->observer->valid())
            $observer = $this->observer->current();


Each observer implements the splobserver interface and implements the update () method

class cat implements SplObserver {

    public function update(SplSubject $subject)
        Echo 'kitten bark';
class dog implements SplObserver {
    public function update(SplSubject $subject)
        Echo 'puppy roar';


//Real time observation
$user = new user();
$user->attach(new cat());
$user->attach(new dog());

The above is the details of parsing PHP observer mode. For more information about PHP observer mode, please pay attention to other related articles of developeppaer!