| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- <?php
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // +----------------------------------------------------------------------
- // | 全局缓存类
- // +----------------------------------------------------------------------
- namespace addons\cms\library;
- use think\facade\Cache;
- class Cache_factory
- {
- protected static $instance = null;
- protected $cacheList = [
- 'Category' => [
- 'name' => '栏目索引',
- 'model' => 'Category',
- 'action' => 'category_cache',
- ],
- 'Model' => [
- 'name' => '模型列表',
- 'model' => 'Models',
- 'action' => 'model_cache',
- ],
- 'ModelField' => [
- 'name' => '模型字段',
- 'model' => 'ModelField',
- 'action' => 'model_field_cache',
- ],
- ];
- /**
- * @param 缓存实例化
- * @return static
- */
- public static function instance($options = [])
- {
- if (is_null(self::$instance)) {
- self::$instance = new self($options);
- }
- return self::$instance;
- }
- /**
- * 获取缓存
- * @param type $name 缓存名称
- * @return null
- */
- public function get($name)
- {
- $cache = Cache::get($name);
- if (!empty($cache)) {
- return $cache;
- } else {
- //尝试生成缓存
- return $this->runUpdate($name);
- }
- return null;
- }
- /**
- * 写入缓存
- * @param string $name 缓存变量名
- * @param type $value 存储数据
- * @param type $expire 有效时间(秒)
- * @return boolean
- */
- public function set($name, $value, $expire = null)
- {
- return Cache::tag('cms')->set($name, $value, $expire);
- }
- /**
- * 删除缓存
- * @param string $name 缓存变量名
- * @return boolean
- */
- public function remove($name)
- {
- return Cache::delete($name);
- }
- /**
- * 更新缓存
- * @param type $name 缓存key
- * @return boolean
- */
- public function runUpdate($name)
- {
- if (empty($name)) {
- return false;
- }
- //查询缓存key
- $cacheList = $this->cacheList;
- foreach ($cacheList as $k => $v) {
- $modelClass = "\\addons\\cms\\model\\{$v['model']}";
- $model = new $modelClass;
- if ($v['action']) {
- $action = $v['action'];
- $model->$action(); //执行方法
- }
- }
- //再次加载
- return Cache::get($name);
- }
- }
|