Example of the Observer pattern for PHP design Patterns

Source: Internet
Author: User
Tags spl
First understand the concept of the Observer pattern: an object is made observable by adding a method that allows another object, the observer to register itself. When an observable object changes, it sends the message to the registered observer. These observers use this information to perform operations that are independent of observable objects. The result is that objects can talk to each other without knowing why. The Observer pattern is an event system, meaning that this pattern allows a class to observe the state of another class, and when the observed class state changes, the observation class can receive notifications and act accordingly; observer patterns provide you with the ability to avoid tight coupling between components.

UML Structure diagram:

The problem that the Observer pattern solves

In our development process, it should be more or less encountered changes in some of the code will cause a series of other changes in the problem, obviously want to completely avoid this situation is unlikely, but we also answer to minimize the dependence on other components, and the observer pattern is to solve the 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 () {//...} Posting method Public Function Addpost () {//... Post Logic}}

In the above is an ordinary post object, with the volume of posts and access to more and more, the operators began to quit, the company also often received a complaint phone, said our site has many sensitive content and spam ads, so we need to do content audit: First, the user's audit, some blacklist users should be banned from posting The second is the audit of IP, and the third is the audit of content-sensitive words. So our code looks like this:

Class post{protected $_userid = null;protected $_ip = null;protected $_content = null;function __construct () {}public funct Ion 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 are required to be audited, the Addpost method becomes more and more long, and the published object can only be embedded tightly into the system.

The implementation of the Observer pattern

The core of the observer pattern is to separate the observer from the subject, and when the subject knows that the event occurs, the observation needs to be notified, and we do not want to write the relationship between the subject and the observer dead, so we modify the code above:

The principal must implement an interface interface Observable {public function attach (Observer $observer);p ublic function Detach (Observer $observer) ;p ublic function Notify ();} The observer must implement an interface interface Observer {public function do (Observable $subject);} Class Post implements observable{protected $_userid = null;protected $_ip = null;protected $_content = null;protected $_ob serverlist = Array (), function __construct () {}public function attach (Observer $observer) {$this->_observerlist[] = $ Observer;} Public Function Detach (Observer $observer) {foreach ($this->_observerlist as $key = = $value) {if ($observer = = = = = $valu e) {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 code above, we can easily join the audit rules.

SPL Code

The Observer pattern is a very common and common design pattern, so that the SPL extension has encapsulated the corresponding classes and methods for us, and the following code is based on the 3 elements provided by SPL: code implemented by Splobserver,splsubject,splobjectstorage

Class Post implements splsubject{protected $_userid = null;protected $_ip = null;protected $_content = null;protected $_st Orage = 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;} // ... }}

Quite simply, the most important thing is to understand that in this example, we have stripped away some of the auditing methods from the Post class, and the Post object can be used as another release type.

The above content implementation is small to introduce you to the PHP design mode of the Observer mode, I hope to help you!

The above describes the PHP design pattern of the observer pattern example, including the content of the subject, I hope that the PHP tutorial interested in friends to help.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.