Examples of observer patterns for PHP design Patterns

Source: Internet
Author: User
Tags abstract foreach bool mail

This article mainly introduces the PHP design mode of the Observer mode (Observer) detailed introduction and code examples, need friends can refer to the following

"Intent" 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 slave (dependents) mode "Observer pattern structure diagram"       "main role in Observer mode"   1. Abstract theme (Subject) role: Theme roles keep All references to observer objects 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 coupling between the observer and the subject is small; 2. Support for broadcast communications;   Observer mode disadvantage:   Because the Observer is unaware of the existence of other observers, It may be ignorant of the ultimate cost of changing goals. This may cause unexpected updates.     "Observer mode applicable scenario"   when an abstract model has two aspects, one aspect relies 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 schemas"   1. Mediator 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"   code is as follows: <?php  /** * Observer mode * @package Design Patterns/ /** * Abstract Theme role */INT Erface Subject {     /**      * Add a new viewer object to      * @param Observer $observer      */    Public Function attach (Observer $observer);      /**      * Delete a registered observer object      * @param Observer $observer   &nbs P  */    Public Function detach (Observer $observer);      /**      * notify all registered Observer objects      */    Public Function Notifyob Servers (); }  /** * Specific theme Role/class ConcreteSubject implements Subject {      private $_observers;   &NBSP ;   Public Function __construct () {        $this->_observers = Array ();    }      /**      * Add a new Observer object      * @param Observer $observer      */     Public Function attach (Observer $observer) {        return Array_push ($this->_obser Vers, $observer);    }      /** &nbsP    * 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)) {    &NB Sp       return FALSE;        }           unset ($this->_observers[$index]);         return TRUE;    }      /**      * notify all registered Observer objects      */    public F Unction Notifyobservers () {        if (!is_array ($this->_observers)) {            return FALSE;        }           foreach ($this->_observers as $observer) {  &nbs P         $observer->update ();       }           return TRUE;    }  }  /** * Abstract observer Role/interface Observer {     /**      * Update method      */    Public Function update (); }   Class Concreteobserver implements Observer {     /**      * Observer's name      * @var <type>      */    private $_name;       Public function __construct ($name) {        $this->_name = $name;   &nbs P      /**      * Update method      */    Public Function update () {&nbs P       echo ' Observer ', $this->_name, ' has notified.<br/> ';    }  } instantiated 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 model, it is an event system Integration, meaning               This mode allows a class to observe the state of another class, when the observed class state changes, the     *           Observation class can be notified and make the appropriate action; The Observer pattern gives you another way to avoid the tight coupling between the components   *           * 3.1 .2 Key points:   *        1. The Observer-> append the Observer;-> an observer;-> meet the conditions notify the Observer;-> observation conditions   *     & nbsp  2. Observer-> acceptance of observation methods   * 3.1.3 Disadvantage:   * 3.1.4 Observer mode in PHP applications: Many aspects of observer applications in Web development   *         Typical: User registration (authentication mail, user information activation), shopping site under the single mail/SMS notification etc   * 3.1.5php internal support   *        splsubject interface, It represents the object being observed,   *         ITS structure:   *        interface splsubject   * &NB Sp      {  *            public function attach (splobserver $observer) &nb Sp *            public function detach (Splobserver $observer);   *            public function notify ();   *       &NBSP}   *        splobserver interface, which represents the object to act as an observer,   *   &NB Sp     ITS structure:   *        interface splobserver   *        { &N Bsp   *            public function update (Splsubject $subject);   *          /   /**   * User Login-annotation Observer mode  /class user ImplemeNTS Splsubject {   //Registered observer     Public $observers = Array ();      //action type   &NBSP ; CONST Observer_type_register = 1;//registration     CONST observer_type_edit = 2;//edit      /**   &NBS P  * additional observer      * @param splobserver $observer Observer      * @param int $type observation type   &N Bsp  */    Public Function attach (Splobserver $observer, $type)     {        $t his->observers[$type] = $observer;    }      /**      * remove observer      * @param splobserver $observer Observation      * @param int $type observation type      */    Public Function detach (Splobserver $obs Erver, $type)     {        if ($idx = Array_search ($observer, $this->observers[$type], tr UE)         {            unset ($this->observers[$type] [$idx]);        }     {     /**      * to notify Observer     &NBS when conditions are met p;* @param int $type observation type      */    Public Function notify ($type)     {        if (!empty ($this->observers[$type])         {          &NB Sp foreach ($this->observers[$type] as $observer)             {        nbsp       $observer->update ($this);                     {   }      /**      * Add user      * @param str $username user name      * @param str $password password   &N Bsp  * @param str $email mailbox      * @return bool      */    Public Function Addus ER ()     {         //HoldRow SQL          //Database Insert success         $res = true;          //Call Notification observers         $this->notify (self::observer_type_register);           return $res;    }      /**      * user information edit      * @param str $username username &nbsp ;    * @param str $password password      * @param str $email mailbox      * @return bool &nbsp ;    */    Public Function edituser ()     {         //Execute SQL          //Database update successful         $res = true;          //Call Notification observers         $this->notify (Self::observer_type_edit);           return $res;    }}  /** * Observer-Send mail/class Send_mail implements Splobserver  {   /**      * change information for corresponding observers      * @param splsubject $subject      */    Public Function upd Ate (Splsubject $subject)     {        $this->sendmail ($subject->email, $title, $cont ENT);    }      /**      * send mail      * @param str $email email address   &NBS P  * @param str $title mail title      * @param str $content mail content      */    Public fu Nction SendEmail ($email, $title, $content)     {       //calling mail interface, sending mail    }? &G T

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.