Php design pattern observer pattern, design pattern observer

Source: Internet
Author: User

Php design pattern observer pattern, design pattern observer

The core of the observer mode is to separate the customer element (observer) from a central class (subject. When the subject knows that an event occurs, the observer must be notified. At the same time, we do not want to hard encode the relationship between the subject and the observer. To achieve this goal, we can allow the observer to register on the subject.

The observer mode implements a low-coupling, non-intrusive notification and update mechanism.

Scenario: when an event occurs, perform a series of update operations.

EventGenerator.php
<? Phpnamespace Baobab;/*** Class EventGenerator base class, event producer */abstract Class EventGenerator {// The observer is invisible to the event producer, the event owner does not care which observers are interested in the event private $ observers = array ();/*** add Observer */function addObserver (observer $ Observer) {$ this-> observers [] = $ observer;}/*** notify the observer one by one to perform update operations */function Y () {foreach ($ this-> observers as $ observer) {$ observer-> update ();}}}
Observer.php
<? Phpnamespace Baobab;/*** Class Observer, the observed object is the event sender * @ package Baobab */interface Observer {/*** @ param null $ event_info event information * indicates the update operation after the event */function update ($ event_info = null );}

Index. php

Class Event extends \ Baobab \ EventGenerator {/*** triggers a new Event */function trigger () {echo 'event occurred '; $ this-> Policy ();}} /*** Observer 1 */class Observer1 implements \ Baobab \ Observer {function Update ($ event_info = null) {echo 'Update operation code 1 ';}}
/**
* Observer 2
*/Class Observer2 implements \ Baobab \ Observer {function Update ($ event_info = null) {echo 'Update operation code 2'; }}$ event = new Event (); $ event-> addObserver (new Observer1 (); $ event-> addObserver (new Observer2 (); $ event-> trigger ();

 

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.