PHP design pattern-Observer pattern (Observer) detailed introduction and code example

Source: Internet
Author: User
Tags php example

[Intention]

Defines a one-to-many dependency between objects. When the status of an object changes, all objects dependent on it are notified and automatically updated. [GOF95] is also called the Publish-Subscribe mode and Model-View Mode) mode, Source-Listener mode, or Dependents Mode

[Observer mode structure diagram]


[Main role in observer mode]

1. Abstract topic role: the topic role stores all references to the observer object in a collection. Each topic can have any number of observers. Abstract topics provide interfaces for adding and deleting observer objects.
2. Abstract Observer role: defines an interface for all specific observers and updates themselves when the observed topic changes.
3. ConcreteSubject role: stores the relevant status to a specific observer object. When the internal status of a specific topic changes, a notification is sent to all registered observers. A topic role is usually implemented by a specific subclass.
4. concretedObserver role: stores a specific topic object, stores related states, and implements the update interface required by the abstract observer role to ensure that its own status is consistent with that of the topic.

[Advantages and disadvantages of observer mode]

Advantages of observer mode:

1. The coupling between the observer and the topic is small;
2. Supports broadcast communication;

Disadvantages of observer mode:

Since the observer does not know the existence of other observers, it may have no idea about the final cost of changing the target. This may cause unexpected updates.


[Observer mode applicable scenarios]

When an abstract model has two aspects, one of which depends on the other.
When changing an object, you need to change other objects at the same time without knowing how many objects are to be changed.
When an object must notify other objects, it cannot assume who the other objects are. In other words, you do not want these objects to be tightly coupled.

[Observer mode and other mode]

1. Mediator mode: By encapsulating complex update semantics, ChangeManager acts as the intermediary between the target and the observer.
2. singleton mode: ChangeManager can use Singleton mode to ensure that it is unique and globally accessible.


[Observer mode PHP example]

Copy codeThe Code is as follows:
<? Php

/**
* Observer Mode
* @ Package design pattern
*/

/**
* Abstract topic role
*/
Interface Subject {

/**
* Adds a new observer object.
* @ Param Observer $ observer
*/
Public function attach (Observer $ observer );

/**
* Delete A registered observer object
* @ Param Observer $ observer
*/
Public function detach (Observer $ observer );

/**
* Notify all registered observer objects
*/
Public function yyobservers ();
}

/**
* Specific topic roles
*/
Class ConcreteSubject implements Subject {

Private $ _ observers;

Public function _ construct (){
$ This-> _ observers = array ();
}

/**
* Adds a new observer object.
* @ Param Observer $ observer
*/
Public function attach (Observer $ observer ){
Return array_push ($ this-> _ observers, $ observer );
}

/**
* Delete A registered observer object
* @ 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;
}

/**
* Notify all registered observer objects
*/
Public function policyobservers (){
If (! Is_array ($ this-> _ observers )){
Return FALSE;
}

Foreach ($ this-> _ observers as $ observer ){
$ Observer-> update ();
}

Return TRUE;
}

}

/**
* Abstract observer role
*/
Interface Observer {

/**
* Update Method
*/
Public function update ();
}

Class ConcreteObserver implements Observer {

/**
* Observer name
* @ Var <type>
*/
Private $ _ name;

Public function _ construct ($ name ){
$ This-> _ name = $ name;
}

/**
* Update Method
*/
Public function update (){
Echo 'observer', $ this-> _ name, 'has notified. <br/> ';
}

}
Instantiation class:
$ Subject = new ConcreteSubject ();

/* Add the first observer */
$ Observer1 = new ConcreteObserver ('martin ');
$ Subject-> attach ($ observer1 );

Echo '<br/> The First week Y: <br/> ';
$ Subject-> policyobservers ();

/* Add the second Observer */
$ Observer2 = new ConcreteObserver ('phppany ');
$ Subject-> attach ($ observer2 );

Echo '<br/> The Second policy: <br/> ';
$ Subject-> policyobservers ();

/* Delete the first observer */
$ Subject-> detach ($ observer1 );

Echo '<br/> The Third Policy: <br/> ';
$ Subject-> policyobservers ();
Case study:

<? Php
/**
* 3.1php design mode-Observer Mode
* 3.1.1 concept: in fact, the observer mode is an easy-to-understand mode. It is an event system, meaning
* This mode allows a class to observe the status of another class. When the observed class status changes,
* The Observer class can receive notifications and make corresponding actions. The observer mode allows you to avoid inter-component
* Another method of tight coupling
* 3.1.2 key points:
* 1. Observer-> append observer;-> one observer;-> notify Observer when the condition is met;-> observation Condition
* 2. Observer-> Accept observation method
* 3.1.3 disadvantages:
* 3.1.4 application of the observer mode in PHP: There are many observer applications in web development.
* Typical: User Registration (verification email, activation of user information), email/SMS notification when a shopping website places an order
* 3.1.5php internal support
* SplSubject interface, which represents the observed object,
* Structure:
* Interface SplSubject
*{
* Public function attach (SplObserver $ observer );
* Public function detach (SplObserver $ observer );
* Public function Y ();
*}
* SplObserver interface, which represents the object that acts as the observer,
* Structure:
* Interface SplObserver
*{
* Public function update (SplSubject $ subject );
*}
*/

/**
* User Login-interpreting observer Mode
*/
Class User implements SplSubject {
// Register the observer
Public $ observers = array ();

// Action Type
CONST OBSERVER_TYPE_REGISTER = 1; // register
CONST OBSERVER_TYPE_EDIT = 2; // Edit

/**
* Append the observer.
* @ Param SplObserver $ observer
* @ Param int $ type observation type
*/
Public function attach (SplObserver $ observer, $ type)
{
$ This-> observers [$ type] [] = $ observer;
}

/**
* Remove the observer
* @ Param SplObserver $ observer
* @ Param int $ type observation type
*/
Public function detach (SplObserver $ observer, $ type)
{
If ($ idx = array_search ($ observer, $ this-> observers [$ type], true ))
{
Unset ($ this-> observers [$ type] [$ idx]);
}
}

/**
* Notify the observer when conditions are met
* @ Param int $ type observation type
*/
Public function notify ($ type)
{
If (! Empty ($ this-> observers [$ type])
{
Foreach ($ this-> observers [$ type] as $ observer)
{
$ Observer-> update ($ this );
}
}
}

/**
* Add a user
* @ Param str $ username
* @ Param str $ password
* @ Param str $ email
* @ Return bool
*/
Public function addUser ()
{

// Execute SQL

// The database is successfully inserted.
$ Res = true;

// Call the notification observer
$ This-> Policy (self: OBSERVER_TYPE_REGISTER );

Return $ res;
}

/**
* Edit user information
* @ Param str $ username
* @ Param str $ password
* @ Param str $ email
* @ Return bool
*/
Public function editUser ()
{

// Execute SQL

// The database is updated successfully.
$ Res = true;

// Call the notification observer
$ This-> Policy (self: OBSERVER_TYPE_EDIT );

Return $ res;
}
}

/**
* Observer-send email
*/
Class Send_Mail implements SplObserver
{
/**
* Change information of the observer
* @ Param SplSubject $ subject
*/
Public function update (SplSubject $ subject)
{
$ This-> sendMail ($ subject-> email, $ title, $ content );
}

/**
* Send an email
* @ Param str $ email address
* @ Param str $ title: email title
* @ Param str $ content
*/
Public function sendEmail ($ email, $ title, $ content)
{
// Call the mail interface to send emails
}
}
?>

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.