Observer code examples of PHP design patterns (27)

Time:2020-11-23

objective

When the state of an object changes, all objects that depend on it are notified and automatically updated. It uses a low coupling approach.

example

  • If the content is good, I hope you can support and encourage you to click like / like, and you are welcome to exchange views. In addition, if you have any questions and want to see the content, you can put forward them in the comments

be careful!

PHP has defined two interfaces to implement the observer pattern quickly: splobserver and splsubject.

UML diagram

The official PHP advanced learning exchange community “click” manages and sorts out some materials. Bat and other first-line factories have advanced knowledge systems (related learning materials and written test questions) and are not limited to: distributed architecture, high scalability, high performance, high concurrency, server performance tuning, tp6, laravel, yii2, redis, swote, soft, Kafka, MySQL optimization, shell script, dock Er, micro service, nginx and other knowledge points

code

  • User.php
observers = new \SplObjectStorage();
    }

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

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

    public function changeEmail(string $email)
    {
        $this->email = $email;
        $this->notify();
    }

    public function notify()
    {
        /** @var \SplObserver $observer */
        foreach ($this->observers as $observer) {
            $observer->update($this);
        }
    }
}
  • UserObserver.php
changedUsers[] = clone $subject;
    }

    /**
 * @return User[]
 */
    public function getChangedUsers(): array
    {
        return $this->changedUsers;
    }
}

test

  • Tests/ObserverTest.php
attach($observer);

        $user->changeEmail('[email protected]');
        $this->assertCount(1, $observer->getChangedUsers());
    }
}

PHP Internet architect’s way to grow * “design patterns” Ultimate Guide

PHP Internet architect 50K growth Guide + general outline of industry problem solving (continuously updated)

Interview 10 companies, get 9 offers, PHP interview questions in 2020

If you like my article and want to communicate and learn with more senior developers, you can get more technical advice and guidance related to interview with large factories. Welcome to join our group, code: phpzh (junyang number: 856460874).

The latest PHP advanced tutorial 2020, full series!

If the content is good, I hope you can support and encourage you to click like / like, and you are welcome to exchange views. In addition, if you have any questions, you can suggest the content you want to see in the comments