


Introduction to the Observer Pattern in PHP Design Patterns_PHP Tutorial
Jul 21, 2016 pm 03:20 PM
Introduction
The observer pattern defines one-to-many dependencies of objects, so that when an object changes state, all its dependents will be notified and automatically updated!
Design principles
In the observer In mode, what changes is the status of the subject and the number of observers. Using this pattern, you can change objects that depend on the theme's state without changing the theme. ——Find out the changing aspects of the program, and then separate them from the fixed aspects!
Both the subject and the observer use interfaces: the observer uses the subject's interface to register with the subject, and the subject uses the observer interface Notify observers. This allows the two to operate normally while having the advantage of loose coupling! ——For interface programming, not implementation programming!
.
The observer pattern uses "composition" to combine many observers into a theme. This relationship between objects (observers - subjects) is not generated through inheritance, but through composition at runtime. ——Use more combination and less inheritance!
Code
<?php
/**
* Observer Pattern
* @author: Mac
* @date: 2012/02/22
* /
class Paper{ /* Topic*/
private $_observers = array();
public function register($sub){ /* Register observers*/
$this->_observers [] = $sub;
}
public function trigger(){ /* External unified access*/
if(!empty($this->_observers)){
foreach($this ->_observers as $observer){
$observer->update();
}
}
}
}
/**
* The interface to be implemented by the observer
*/
interface Observerable{
public function update();
}
class Subscriber implements Observerable{
public function update(){
echo "Callbackn";
}
}
//The following is the test code
?
/* Test*/
$paper = new Paper();
$paper->register(new Subscriber());
//$paper->register(new Subscriber1());
//$paper->register(new Subscriber2());
$paper->trigger();
Summary
When a new object is to be filled in, it only needs to be registered in the subject (also called an observable) (there are many ways to register, you can also do it during construction , or register in the interface accessed by the framework), and then implement the code directly in the interface of the new object. This reduces the coupling between subject and observer objects.
Good design patterns don’t go directly into your code, they go into your brain.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

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 Installation and Upgrade guide for Ubuntu and Debian

How To Set Up Visual Studio Code (VS Code) for PHP Development
