PHP design pattern Observer pattern example
First understand the concept of the Observer pattern: an object makes itself observable by adding a method that allows another object, an observer, to register itself. When an observable object changes, it sends messages to registered observers. These observers use this information to perform operations independent of the observable object. The result is that objects can talk to each other without having to understand why. The observer pattern is an event system, which means that this pattern allows a class to observe the state of another class. When the state of the observed class changes, the observing class can receive notifications and take corresponding actions; observation The operator pattern provides you with the ability to avoid tight coupling between components.
UML structure diagram:
Problems solved by the observer pattern
In our development process, we should have more or less encountered the problem that changing part of the code will cause a series of other changes. Obviously we want to It is unlikely to completely avoid this situation, but we should also try to reduce dependencies on other components as much as possible, and the observer pattern is designed to solve this problem.
For example, we have a post object with the following code:
class Post { protected $_userid = null; protected $_ip = null; protected $_content = null; function __construct() { // ... } // 发帖方法 public function addPost() { // ... 发帖逻辑 } }
The above is an ordinary post object. As the number of posts and visits increases, the operators start to quit. The company also often receives complaint calls saying that our website contains a lot of sensitive content and spam advertisements, so we need to conduct content review: first, review of users, some blacklisted users should be prohibited from posting; second, review of IP ; The third is the review of content-sensitive words. So our code looks like the following:
class Post { protected $_userid = null; protected $_ip = null; protected $_content = null; function __construct() { } public function addPost() { if (!Postscan::checkUserid($tihs->_userid)) { return false; } if (!Postscan::ipUserid($tihs->_ip)) { return false; } if (!Postscan::checkContent($tihs->_content)) { return false; } // ... } }
As more and more fields need to be reviewed, the addPost method becomes longer and longer, and the publishing object can only be tightly embedded in the system. middle.
Implementation of Observer Pattern
The core of the observer pattern is to separate the observer from the subject. When the subject knows that an event occurs, the observer needs to be notified. At the same time, we do not want to create a conflict between the subject and the observer. The relationship is hard-coded, so let’s modify our code above:
//主体必须实现的接口 interface Observable { public function attach(Observer $observer); public function detach(Observer $observer); public function notify(); } //观察者必须实现的接口 interface Observer { public function do(Observable $subject); } class Post implements Observable { protected $_userid = null; protected $_ip = null; protected $_content = null; protected $_observerlist = array(); function __construct() { } public function attach(Observer $observer) { $this->_observerlist[] = $observer; } public function detach(Observer $observer) { foreach ($this->_observerlist as $key => $value) { if ($observer === $value) { unset($this->_observerlist[$key]) } } } public function notify() { foreach ($this->_observerlist as $value) { if (!$value->do($this)) { return false; } } return true; } public function addPost() { if (!$this->notify()) { return false; } // ... } }
With the above code, we can easily add audit rules.
SPL code
The observer pattern is a very common and commonly used design pattern, so much so that the SPL extension has encapsulated the corresponding classes and methods for us. The following code is based on the three elements provided by SPL: SplObserver, SplSubject , the code implemented by SplObjectStorage
class Post implements SplSubject { protected $_userid = null; protected $_ip = null; protected $_content = null; protected $_storage = new SplObjectStorage(); function __construct() { } public function attach(SplObject $observer) { $this->_storage->attach($observer); } public function detach(SplObject $observer) { $this->_storage->detach($observer); } public function notify() { foreach ($this->_storage as $value) { if (!$value->update($this)) { return false; } } return true; } public function addPost() { if (!$this->notify()) { return false; } // ... } }
is very simple. The most important thing is to understand that in this example, we have separated some auditing methods from the post class, and the post object can also be used as Other publishing types.
The implementation of the above content is the observer mode of PHP design pattern introduced by the editor to you. I hope it will be helpful to everyone!
The above introduces the observer pattern example of PHP design pattern, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Every year before Apple releases a new major version of iOS and macOS, users can download the beta version several months in advance and experience it first. Since the software is used by both the public and developers, Apple has launched developer and public versions, which are public beta versions of the developer beta version, for both. What is the difference between the developer version and the public version of iOS? Literally speaking, the developer version is a developer test version, and the public version is a public test version. The developer version and the public version target different audiences. The developer version is used by Apple for testing by developers. You need an Apple developer account to download and upgrade it.

In JavaScript, both undefined and null represent the concept of "nothing": 1. undefined represents an uninitialized variable or a non-existent property. When a variable is declared but no value is assigned to it, the value of the variable is undefined , when accessing properties that do not exist in the object, the returned value is also undefined; 2. null represents an empty object reference. In some cases, the object reference can be set to null to release the memory it occupies.

The difference between null and NULL in C language is: null is a macro definition in C language, usually used to represent a null pointer, which can be used to initialize pointer variables, or to determine whether the pointer is null in a conditional statement; NULL is a macro definition in C language A predefined constant in , usually used to represent a null value, used to represent a null pointer, null pointer array or null structure pointer.

The difference between null and undefined is: 1. Semantic meaning; 2. Usage scenarios; 3. Comparison with other values; 4. Relationship with global variables; 5. Relationship with function parameters; 6. Nullability check; 7. Performance considerations; 8. Performance in JSON serialization; 9. Relationship with types. Detailed introduction: 1. Semantic meaning, null usually means knowing that this variable will not have any valid object value, while undefined usually means that the variable has not been assigned a value, or the object does not have this attribute; 2. Usage scenarios, etc.

Both null and undefined indicate a lack of value or an undefined state. Depending on the usage scenario, there are some guiding principles for choosing to use null or undefined: 1. When you need to clearly indicate that a variable is empty or invalid, you can use null; 2. When a variable has been declared but not yet assigned a value, it will be set to undefined by default; 3. When you need to check whether a variable is empty or undefined, use the strict equality operator "===" to determine whether the variable is null or undefined. .

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

Detailed explanation of the role and function of the MySQL.proc table. MySQL is a popular relational database management system. When developers use MySQL, they often involve the creation and management of stored procedures (StoredProcedure). The MySQL.proc table is a very important system table. It stores information related to all stored procedures in the database, including the name, definition, parameters, etc. of the stored procedures. In this article, we will explain in detail the role and functionality of the MySQL.proc table
