Definition and Usage Analysis of Observer Pattern in PHP Design Pattern

  • 2021-12-05 05:39:53
  • OfStack

This paper illustrates the definition and usage of observer pattern of PHP design pattern. Share it for your reference, as follows:

Observer mode When the state of an object changes, all objects that depend on it will be notified and updated automatically

Scenario: When an event occurs, to execute a series of update operations, the traditional programming method is to add processing logic directly after the event code. When the update logic increases, the code becomes difficult to maintain. This method is coupled and invasive. Adding new logic requires changing the code of the event subject

The observer mode realizes low coupling and non-invasive notification and update


abstract class EventGenerator
{
  private $ObServers = [];
  // Add observers 
  public function add(ObServer $ObServer)
  {
    $this->ObServers[] = $ObServer;
  }
  // Event notification 
  public function notify()
  {
    foreach ($this->ObServers as $ObServer) {
      $ObServer->update();
    }
  }
}
/**
 *  Observer interface class 
 * Interface ObServer
 */
interface ObServer
{
  public function update($event_info = null);
}
/**
 *  Observer 1
 */
class ObServer1 implements ObServer
{
  public function update($event_info = null)
  {
    echo " Observer 1  Receive the execution notice   End of execution! \n";
  }
}
/**
 *  Observer 1
 */
class ObServer2 implements ObServer
{
  public function update($event_info = null)
  {
    echo " Observer 2  Receive the execution notice   End of execution! \n";
  }
}
/**
 *  Events 
 * Class Event
 */
class Event extends EventGenerator
{
  /**
   *  Trigger event 
   */
  public function trigger()
  {
    // Inform the observer 
    $this->notify();
  }
}
// Create 1 Events 
$event = new Event();
// Add bystanders to the event 
$event->add(new ObServer1());
$event->add(new ObServer2());
// Execution event   Inform bystanders 
$event->trigger();

Run results:

Observer 1 receives the execution notification. Execution is complete!
Observer 2 receives the execution notification. Execution is complete!

1 abstract event generation class, define 1 add observer method, and notify method (execute observer method)

2 Define observer interface, implementation method and observer implementation

3. Define concrete implementation classes to inherit abstract events and implement notification methods

4 Create objects, add bystanders, update

Specific registration instance


<?php
 /**
 * 3.1php设计模式-观测者模式
 * 3.1.1概念:其实观察者模式这是1种较为容易去理解的1种模式吧,它是1种事件系统,意味
 *     着这1模式允许某个类观察另1个类的状态,当被观察的类状态发生改变的时候,
 *     观察类可以收到通知并且做出相应的动作;观察者模式为您提供了避免组件之间
 *     紧密耦合的另1种方法
 * 3.1.2关键点:
 *    1.被观察者->追加观察者;->1处观察者;->满足条件时通知观察者;->观察条件
 *    2.观察者 ->接受观察方法
 * 3.1.3缺点:
 * 3.1.4观察者模式在PHP中的应用场合:在web开发中观察者应用的方面很多
 *    典型的:用户注册(验证邮件,用户信息激活),购物网站下单时邮件/短信通知等
 * 3.1.5php内部的支持
 *    SplSubject 接口,它代表着被观察的对象,
 *    其结构:
 *    interface SplSubject
 *    {
 *      public function attach(SplObserver $observer);
 *      public function detach(SplObserver $observer);
 *      public function notify();
 *    }
 *    SplObserver 接口,它代表着充当观察者的对象,
 *    其结构:
 *    interface SplObserver
 *    {
 *      public function update(SplSubject $subject);
 *    }
 */
 /**
 * 用户登陆-诠释观察者模式
 */
class User implements SplSubject {
  //注册观察者
  public $observers = array();
  //动作类型
  CONST OBSERVER_TYPE_REGISTER = 1;//注册
  CONST OBSERVER_TYPE_EDIT = 2;//编辑
  /**
   * 追加观察者
   * @param SplObserver $observer 观察者
   * @param int $type 观察类型
   */
  public function attach(SplObserver $observer, $type)
  {
    $this->observers[$type][] = $observer;
  }
  /**
   * 去除观察者
   * @param SplObserver $observer 观察者
   * @param int $type 观察类型
   */
  public function detach(SplObserver $observer, $type)
  {
    if($idx = array_search($observer, $this->observers[$type], true))
    {
      unset($this->observers[$type][$idx]);
    }
  }
  /**
   * 满足条件时通知观察者
   * @param int $type 观察类型
   */
  public function notify($type)
  {
    if(!empty($this->observers[$type]))
    {
      foreach($this->observers[$type] as $observer)
      {
        $observer->update($this);
      }
    }
  }
  /**
   * 添加用户
   * @param str $username 用户名
   * @param str $password 密码
   * @param str $email 邮箱
   * @return bool
   */
  public function addUser()
  {
    //执行sql
    //数据库插入成功
    $res = true;
    //调用通知观察者
    $this->notify(self::OBSERVER_TYPE_REGISTER);
    return $res;
  }
  /**
   * 用户信息编辑
   * @param str $username 用户名
   * @param str $password 密码
   * @param str $email 邮箱
   * @return bool
   */
  public function editUser()
  {
    //执行sql
    //数据库更新成功
    $res = true;
    //调用通知观察者
    $this->notify(self::OBSERVER_TYPE_EDIT);
    return $res;
  }
}
/**
* 观察者-发送邮件
*/
class Send_Mail implements SplObserver
{
  /**
   * 相应被观察者的变更信息
   * @param SplSubject $subject
   */
  public function update(SplSubject $subject)
  {
    $this->sendMail($subject->email, $title, $content);
  }
  /**
   *发送邮件
   *@param str $email 邮箱地址
   *@param str $title 邮件标题
   *@param str $content 邮件内容
   */
  public function sendEmail($email, $title, $content)
  {
    //调用邮件接口,发送邮件
  }
}
?>

More readers interested in PHP can check out the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: