php 观察者模式
对比参考: https://www.cnblogs.com/onephp/p/6108344.html
配置文件:
/* * 观察者配置文件 * */ return array( 'init'=>array( 'Common_Controller_CmdLine_Plugin_Article', 'Common_Controller_CmdLine_Plugin_Ad' , 'Common_Controller_CmdLine_Plugin_Thread' , 'Common_Controller_CmdLine_Plugin_LiveBack', ), );
触发脚本
<?php namespace Common\Controller\CmdLine; use KIF\Core\Controller; use SplSubject; use SplObserver; /** * * 首页热点推荐,使用观察者模式,进行分组管理,避免每一次数据更改,都要复制一遍代码,新增计划任务,建立一个单独的版本维护。 * 增加删除类型数据,可以在plugin下配置文件配置,修改对应的组建 * 增加新的组合方式,可以新建事件 */ class AppIndexDataNew extends Controller implements SplSubject { protected $configs; protected $observers; public $event; public function __construct() { $this->configs = include __DIR__ . '/Plugin/config.php'; if(!$this->configs) { self::echo_exit('配置文件错误'); } } public function doInit(){ $this->event = 'init'; $this->notify(); //合并热文和帖子 $redis = new \KIF\Cache\MyRedis(); $redis->zunionstore('AppHomeArticleAThread', array('AppHomeArticles','AppHomeThead', 'AppHomeLiveBack')); self::echo_exit('数据更新完成'); } public function attach(SplObserver $observer) { $this->observers[] = $observer; } public function detach(SplObserver $observer) { if($index = array_search($observer, $this->observers, true)) unset($this->observers[$index]); } public function notify() { if(!$this->observers[$this->event]){ if(!$this->configs[$this->event]) self::echo_exit('该事件不存在'); foreach ($this->configs[$this->event] as $key=>$val){ $val = str_replace('_', '\\', $val); $this->observers[$this->event][] = new $val(); } } foreach ($this->observers[$this->event] as $observer) { $observer->update($this); } } public function run() { $action = $this->action; $this->$action(); } }
观察者
<?php namespace Common\Controller\CmdLine\Plugin; use SplObserver; use SplSubject; use Common\Controller\CmdLine\Plugin\Helper; /* * 管理回放组件 * */ class LiveBack implements SplObserver { protected $Helper; protected $redis; public function __construct() { $this->Helper = new Helper(); } public function update(SplSubject $subject){ $this->{$subject->event}(); } public function init(){ echo '开始回放数据更新',"\r\n"; //获取数据 $data = $this->Helper->getLiveBack(); //压入缓存 $redis = new \KIF\Cache\MyRedis(); $tmp_key = 'tmp_liveBack'; $key = 'AppHomeLiveBack'; if(!$data){ $redis->del($key); echo '没有回放数据',"\n"; return false; } foreach ($data as $k=>$value){ $redis->zadd( $tmp_key, $value['dateline'],serialize($value)); } $redis->rename($tmp_key, $key); echo '回放数据更新完毕',"\r\n"; } }