PHP观察者模式示例【Laravel框架中有用到】

时间:2019-04-20
本文章向大家介绍PHP观察者模式示例【Laravel框架中有用到】,主要包括PHP观察者模式示例【Laravel框架中有用到】使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文实例讲述了PHP观察者模式。分享给大家供大家参考,具体如下:

<?php
//观察者模式
//抽象主题类
interface Subject
{
  public function attach(Observer $Observer);
  public function detach(Observer $observer);
  //通知所有注册过的观察者对象
  public function notifyObservers();
}
//具体主题角色
class ConcreteSubject implements Subject
{
  private $_observers;
  public function __construct()
  {
    $this->_observers = array();
  }
  //增加一个观察者对象
  public function attach(Observer $observer)
  {
    return array_push($this->_observers,$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;
  }
  //通知所有注册过的观察者
  public function notifyObservers()
  {
    if(!is_array($this->_observers)) return false;
    foreach($this->_observers as $observer)
    {
      $observer->update();
    }
    return true;
  }
}
//抽象观察者角色
interface Observer
{
  //更新方法
  public function update();
}
//观察者实现
class ConcreteObserver implements Observer
{
  private $_name;
  public function __construct($name)
  {
    $this->_name = $name;
  }
  //更新方法
  public function update()
  {
    echo 'Observer'.$this->_name.' has notify';
  }
}
$Subject = new ConcreteSubject();
//添加第一个观察者
$observer1 = new ConcreteObserver('baixiaoshi');
$Subject->attach($observer1);
echo 'the first notify:';
$Subject->notifyObservers();
//添加第二个观察者
$observer2 = new ConcreteObserver('hurong');
echo '<br/>second notify:';
$Subject->attach($observer2);
/*echo $Subject->notifyObservers();
echo '<br/>';
$Subject->notifyObservers();*/
?>

运行结果:

the first notify:Observerbaixiaoshi has notify
second notify:

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。