PHP design mode observer mode (OBSERVER) detailed introduction and code instance _php instance

Source: Internet
Author: User
Tags abstract

Intention

Defines a one-to-many dependency between objects, and when the state of an object changes, all objects that depend on it are notified and automatically updated "GOF95", also known as publish-subscribe (publish-subscribe) mode, model-view (model-view) mode, Source-Listener (Source-listener) mode, or dependent (dependents) mode

"Observer pattern structure diagram"


"Main role in observer mode"

1. Abstract theme (Subject) role: Theme roles keep all references to the Observer object in a collection, each subject can have any number of observers. Abstract topics provide an interface for adding and removing observer objects.
2. Abstract observer (OBSERVER) Role: Define an interface for all specific observers and update themselves when the subject of the observation changes.
3. Specific theme (ConcreteSubject) role: Store related states to specific observer objects, and notify all registered observers when the internal state of the specific subject changes. Specific theme roles are usually implemented with a specific subclass.
4. The specific observer (Concretedobserver) Role: stores a specific Subject object, stores the associated state, and implements the update interface required by the abstract observer role to keep its state and subject state consistent.

"The pros and cons of the Observer model"

The advantages of the Observer model:

1. The degree of coupling between the observer and the subject is small;
2. Support for broadcasting communications;

Disadvantages of the Observer model:

Since the observer does not know the existence of other observers, it may be ignorant of the ultimate cost of changing the target. This may cause unexpected updates.


"Observer mode fits the scene"

When an abstract model has two aspects, one aspect is dependent on another.
When a change to an object needs to change the other object at the same time, do not know how many objects to change.
When an object must notify other objects, it cannot assume that the other object is. In other words, you don't want these objects to be tightly coupled.

"Observer mode and other patterns"

1. Intermediary mode (mediator): Changemanager acts as an intermediary between the target and the observer by encapsulating the complex update semantics.
2. Single case mode (singleton mode): Changemanager can use singleton mode to ensure that it is unique and globally accessible.


"Observer mode PHP sample"

Copy Code code as follows:

<?php

/**
* Observer mode
* @package Design
*/

/**
* Abstract Theme Roles
*/
Interface Subject {

/**
* Add 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 notifyobservers ();
}

/**
* Specific Theme Roles
*/
Class ConcreteSubject implements Subject {

Private $_observers;

Public Function __construct () {
$this->_observers = Array ();
}

/**
* Add 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 notifyobservers () {
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 {

/**
* Name of the Observer
* @var <type>
*/
Private $_name;

Public function __construct ($name) {
$this->_name = $name;
}

/**
* Update method
*/
Public Function Update () {
Echo ' Observer ', $this->_name, ' has notified.<br/> ';
}

}
Instantiate class:
$subject = new ConcreteSubject ();

* * ADD first observer/
$observer 1 = new Concreteobserver (' Martin ');
$subject->attach ($observer 1);

Echo ' <br/> The ' notify:<br/> ';
$subject->notifyobservers ();

* * Add a second observer/
$observer 2 = new Concreteobserver (' Phppan ');
$subject->attach ($observer 2);

Echo ' <br/> The Second notify:<br/> ';
$subject->notifyobservers ();

/* Delete the first observer * *
$subject->detach ($observer 1);

Echo ' <br/> The third notify:<br/> ';
$subject->notifyobservers ();
Specific cases:

<?php
/**
* 3.1php design mode-Observer mode
* 3.1.1 Concept: In fact, observer mode this is a relatively easy to understand a pattern bar, it is an event system, meaning
* This pattern allows a class to observe the state of another class, and when the observed class state changes,
* Observation class can receive notification and make corresponding action; The Observer mode provides you with the avoidance of component
* Another method of tight coupling
* 3.1.2 Key points:
* 1. Observers-> additional observers;-> an observer;-> to meet the conditions to notify the Observer;-> observation conditions
* 2. Observer-> accepted observation method
* 3.1.3 Disadvantages:
* Application of the 3.1.4 Observer pattern in PHP: Many aspects of the application of observers in Web development
* Typical: User registration (verification of mail, user information activation), shopping site under a single email/SMS notification, etc.
* 3.1.5php Internal support
* Splsubject interface, which represents the object being observed,
* Its structure:
* Interface Splsubject
*        {
* Public Function Attach (Splobserver $observer);
* Public Function Detach (Splobserver $observer);
* Public function notify ();
*        }
* Splobserver interface, which represents an object that acts as an observer,
* Its structure:
* Interface Splobserver
*        {
* Public Function Update (Splsubject $subject);
*        }
*/

/**
* User Login-Interpreting observer mode
*/
Class User implements Splsubject {
Registered Observer
Public $observers = Array ();

Action type
CONST Observer_type_register = 1;//Registration
CONST Observer_type_edit = 2;//Edit

   /**
     * Append observer
     * @param splobserver $ Observer Observer
     * @param int $type observation Type
     */
    Public function Attach (Splobserver $observer, $type)
    {
         $this->observers[$type] = $observer;
   }

   /**
     * Removal Observer
     * @param splobserver $ Observer 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 observers 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 Users
* @param str $username user name
* @param str $password password
* @param str $email mailbox
* @return BOOL
*/
Public Function AddUser ()
{

Execute SQL

Database Insert Succeeded
$res = true;

Call Notification Viewer
$this->notify (Self::observer_type_register);

return $res;
}

/**
* User Information editing
* @param str $username user name
* @param str $password password
* @param str $email mailbox
* @return BOOL
*/
Public Function Edituser ()
{

Execute SQL

Database Update Successful
$res = true;

Call Notification Viewer
$this->notify (Self::observer_type_edit);

return $res;
}
}

/**
* Observer-Send mail
*/
Class Send_mail implements Splobserver
{
/**
* Change information of the corresponding observed person
* @param splsubject $subject
*/
Public Function Update (Splsubject $subject)
{
$this->sendmail ($subject->email, $title, $content);
}

/**
* Send mail
* @param str $email email address
* @param str $title message headers
* @param str $content mail content
*/
Public Function SendEmail ($email, $title, $content)
{
Call Mail interface, send mail
}
}
?>

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.