PHP observer pattern
Concept
The observer pattern is a behavioral pattern that defines a one-to-many dependency relationship between objects, so that when the state of an object changes, all objects that depend on it are notified and automatically refreshed.
When the state of an object changes, it will affect the changes of several other objects. At this time, the observer mode can be used.
The observer pattern complies with the interface isolation principle and achieves loose coupling between objects.
Alias
Publish-Subscribe> Pattern
Model-View
Source-Listener> Pattern
Slave Pattern
Role
Abstract Subject (Subject): It keeps references to all observer objects in a collection, and each subject can have any number of observers. The abstract theme provides an interface to add and remove observer objects.
Concrete Subject (ConcreteSubject): Store the relevant status in a specific observer object; when the internal status of the specific subject changes, a notification is sent to all registered observers.
Abstract Observer (Observer): Define an interface for all concrete observers and update themselves when notified by the topic.
Concrete Observer: Implement the update interface required by the abstract observer role in order to coordinate its own state with the subject state.
UML diagram
Code
Sample code
The SplSubject and SqlOberver interfaces have been provided in PHP SPL. The source code is as follows:
/** * The <b>SplSubject</b> interface is used alongside * <b>SplObserver</b> to implement the Observer Design Pattern. * @link http://php.net/manual/en/class.splsubject.php */ interface SplSubject { /** * Attach an SplObserver * @link http://php.net/manual/en/splsubject.attach.php * @param SplObserver $observer <p> * The <b>SplObserver</b> to attach. * </p> * @return void * @since 5.1.0 */ public function attach (SplObserver $observer); /** * Detach an observer * @link http://php.net/manual/en/splsubject.detach.php * @param SplObserver $observer <p> * The <b>SplObserver</b> to detach. * </p> * @return void * @since 5.1.0 */ public function detach (SplObserver $observer); /** * Notify an observer * @link http://php.net/manual/en/splsubject.notify.php * @return void * @since 5.1.0 */ public function notify (); } /** * The <b>SplObserver</b> interface is used alongside * <b>SplSubject</b> to implement the Observer Design Pattern. * @link http://php.net/manual/en/class.splobserver.php */ interface SplObserver { /** * Receive update from subject * @link http://php.net/manual/en/splobserver.update.php * @param SplSubject $subject <p> * The <b>SplSubject</b> notifying the observer of an update. * </p> * @return void * @since 5.1.0 */ public function update (SplSubject $subject); }
Now we write our own code based on these two spl interfaces:
<?php header('Content-type:text/html;charset=utf-8'); /** * Class Subject 主题 */ class Subject implements SplSubject { private $_observers = []; /** * 实现添加观察者方法 * * @param SplObserver $observer */ public function attach(SplObserver $observer) { if (!in_array($observer, $this->_observers)) { $this->_observers[] = $observer; } } /** * 实现移除观察者方法 * * @param SplObserver $observer */ public function detach(SplObserver $observer) { if (false !== ($index = array_search($observer, $this->_observers))) { unset($this->_observers[$index]); } } /** * 实现提示信息方法 */ public function notify() { foreach ($this->_observers as $observer) { $observer->update($this); } } /** * 设置数量 * * @param $count */ public function setCount($count) { echo "数据量加" . $count . '<br>'; } /** * 设置积分 * * @param $integral */ public function setIntegral($integral) { echo "积分量加" . $integral . '<br>'; } } /** * Class Observer1 观察者一 */ class Observer1 implements SplObserver { public function update(SplSubject $subject) { $subject->setCount(10); } } /** * Class Observer2 观察者二 */ class Observer2 implements SplObserver { public function update(SplSubject $subject) { $subject->setIntegral(10); } } /** * Class Client 客户端 */ class Client { /** * 测试方法 */ public static function test() { // 初始化主题 $subject = new Subject(); // 初始化观察者一 $observer1 = new Observer1(); // 初始化观察者二 $observer2 = new Observer2(); // 添加观察者一 $subject->attach($observer1); // 添加观察者二 $subject->attach($observer2); // 消息提示 $subject->notify();//输出:数据量加1 积分量加10 // 移除观察者一 $subject->detach($observer1); // 消息提示 $subject->notify();//输出:数据量加1 积分量加10 积分量加10 } } // 执行测试 Client::test();
Running results
The amount of data plus 10
The amount of points plus 10
The amount of points plus 10
Advantages and disadvantages
Advantages
The coupling between the observer and the subject is small;
Supports broadcast communication;
Disadvantages
Since the observer is not aware of the existence of other observers, it may not know the ultimate cost of changing the target. This may cause unexpected updates.
Applicable scenarios
When an abstract model has two aspects, one of which depends on the other.
When changes to one object require changes to other objects at the same time, you don’t know how many objects need to be changed.
When an object must notify other objects, it cannot assume who the other objects are. In other words, you don't want these objects to be tightly coupled.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
