Detailed explanation of php observer pattern
This article mainly introduces the detailed explanation of the PHP observer mode. Interested friends can refer to it. I hope it will be helpful to everyone.
1. Intention
Define a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it All objects are notified and automatically updated [GOF95]
Also known as publish-subscribe (Publish-Subscribe) mode, model-view (Model-View) mode, source-listener (Source-Listener) mode, or slave Dependents pattern
2. Observer pattern structure diagram
#3. The main role in the observer patternAbstract subject (Subject) role:The subject role saves all references to the observer object in a collection, each subject There can be any number of observers. The abstract theme provides an interface for adding and removing observer objects.
Abstract Observer (Observer) role: Define an interface for all specific observers and update themselves when the subject of observation changes.
Concrete subject (ConcreteSubject) role: Store the relevant state to the specific observer object. When the internal state of the specific subject changes, notify all registered observers. Concrete theme roles are usually implemented using a concrete subclass.
Concrete Observer (ConcretedObserver) role: Store a specific subject object, store related states, and implement the update interface required by the abstract observer role to make its own state consistent with the state of the subject.
4. Advantages and disadvantages of the observer pattern
Advantages of the observer pattern:1. The degree of coupling between the observer and the subject Smaller; 2. Supports broadcast communication;
Disadvantages of the observer mode:
1. Since the observer does not know the existence of other observers, it may have a negative impact on the final cost of changing the target. Nothing is known. This may cause unexpected updates.
5. Applicable scenarios of the observer pattern1. When an abstract model has two aspects, one of which depends on the other. 2. When changing one object requires changing other objects at the same time, it is not known how many objects need to be changed. 3. 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.
6. Observer pattern and other patternsMediator pattern (Mediator):By encapsulating complex update semantics, ChangeManager acts as a target and an observer. intermediary between. Singleton mode (singleton mode):
ChangeManager can use the Singleton mode to ensure that it is unique and globally accessible.
7. Observer Mode PHP Example<?php
/**
* 抽象主题角色
*/
interface Subject {
/**
* 增加一个新的观察者对象
* @param Observer $observer
*/
public function attach(Observer $observer);
/**
* 删除一个已注册过的观察者对象
* @param Observer $observer
*/
public function detach(Observer $observer);
/**
* 通知所有注册过的观察者对象
*/
public function notifyObservers();
}
/**
* 具体主题角色
*/
class ConcreteSubject implements Subject {
private $_observers;
public function __construct() {
$this->_observers = array();
}
/**
* 增加一个新的观察者对象
* @param Observer $observer
*/
public function attach(Observer $observer) {
return array_push($this->_observers, $observer);
}
/**
* 删除一个已注册过的观察者对象
* @param Observer $observer
*/
public function detach(Observer $observer) {
$index = array_search($observer, $this->_observers);
if ($index === FALSE || ! array_key_exists($index, $this->_observers)) {
return FALSE;
}
unset($this->_observers[$index]);
return TRUE;
}
/**
* 通知所有注册过的观察者对象
*/
public function notifyObservers() {
if (!is_array($this->_observers)) {
return FALSE;
}
foreach ($this->_observers as $observer) {
$observer->update();
}
return TRUE;
}
}
/**
* 抽象观察者角色
*/
interface Observer {
/**
* 更新方法
*/
public function update();
}
class ConcreteObserver implements Observer {
/**
* 观察者的名称
* @var <type>
*/
private $_name;
public function __construct($name) {
$this->_name = $name;
}
/**
* 更新方法
*/
public function update() {
echo 'Observer', $this->_name, ' has notified.<br />';
}
}
/**
* 客户端
*/
class Client {
/**
* Main program.
*/
public static function main() {
$subject = new ConcreteSubject();
/* 添加第一个观察者 */
$observer1 = new ConcreteObserver('Martin');
$subject->attach($observer1);
echo '<br /> The First notify:<br />';
$subject->notifyObservers();
/* 添加第二个观察者 */
$observer2 = new ConcreteObserver('phppan');
$subject->attach($observer2);
echo '<br /> The Second notify:<br />';
$subject->notifyObservers();
/* 删除第一个观察者 */
$subject->detach($observer1);
echo '<br /> The Third notify:<br />';
$subject->notifyObservers();
}
}
Client::main();
?>
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's learning.
Related recommendations:
PHP method to implement asterisk to hide username, mobile phone and email addressphp WeChat public platform configuration interface development Detailed explanation of the method examples of the programDetailed explanation of the method of PHP implementation of the previous article and the next articleThe above is the detailed content of Detailed explanation of php observer pattern. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment