search
HomeBackend DevelopmentPHP TutorialPHP design patterns: Observer pattern Observer design pattern application java Observer design pattern Design pattern Decorator pattern

Introduction to the Observer Pattern

The Observer pattern (Observer) perfectly separates the observer from the observed object. For example, the user interface can serve as an observer, and the business data is the observed. The user interface observes changes in the business data, and after discovering changes in the data, it is displayed on the interface. One principle of object-oriented design is that each class in the system will focus on a certain function rather than other aspects. An object does one thing and does it well. The Observer pattern draws clear boundaries between modules, improving the maintainability and reusability of applications.

The observer design pattern 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.

Implementation methods

There are many ways to implement the observer pattern. Fundamentally, this pattern must contain two roles: the observer and the observed object. In PHP, the SplSubject and SplObserver interfaces are used to implement the observer pattern.

SplSubject Observed Object

SplSubject {
/* 方法 */
abstract public void attach ( SplObserver $observer ) //将被观察对象注册到观察者中
abstract public void detach ( SplObserver $observer ) //被观察对账取消注册
abstract public void notify ( void )  //通知所有观察者
}

SplObserver Observer

SplObserver {
/* 方法 */
abstract public void update ( SplSubject $subject ) //观察者接受到通知的时候,作出相应改变
}

UML Class Diagram

设计模式 观察者模式,观察者模式 事件模式,策略模式 观察者模式,c#观察者设计模式,观察者模式 命令模式,观察者设计模式应用,java 观察者设计模式,设计模式 装饰者模

Example

Give an example of user registration. After the user registration is successful, the user's data needs to be saved to the database. and sends an email to the user. Use observer code to implement:

When the registration is successful, the observer calls the notify method to notify all observers.

function _main()
{
	$user = new User('zhibin','zhibin');
	$user->attach(new UserDatabase());
	$user->attach(new UserMail());
	$user->notify();
}
class User implements SplSubject
{
	/**
	* 帐号
	* @var string
	*/
	private $_user_name;
	/**
	* 密码
	* @var string
	*/
	private $_password;
	/**
	* 观察者列表
	* @var array
	*/
	private $_observers;
	
	public function __construct($user_name,$password)
	{
		$this->_user_name = $user_name;
		$this->_password = $password;
		$this->_observers = array();
	}
	
	public function attach(SplObserver $obs)
	{
		array_push($this->_observers,$obs);
	}
	
	public function detach(SplObserver $obs)
	{
		if($key = array_search($obs,$this->_observers,true))
		{
			unset($this->_observers[$key]);
		}
	}
	
	public function notify()
	{
		foreach($this->_observers as $obs)
		{
			$obs->update($this);
		}
	}
}

class UserDatabase implements SplObserver
{
	public function update(SplSubject $sub)
	{
		//update database
		echo 'update database'.PHP_EOL;
	}
}

class UserMail implements SplObserver
{
	public function update(SplSubject $sub)
	{
		//send mail to user
		echo 'send mail to user'.PHP_EOL;
	}
}
_main();

The above introduces the PHP design pattern: the observer pattern, including the observer pattern and design pattern. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools