实现File缓存统一管理

浏览:1061 发布日期:2013/08/04 分类:技术分享
经过测试与考虑,我觉得没必要采用第三方类,经测试内存占用比直接调用Cache::getInstance大。所以我觉得应该将缓存配置方案写到配置文件中,MyCache()函数可以保留,直接读取配置,使用Cache::getInstance实例化即可。

即,我这篇文章多余了,客官们看了一笑置之吧

==========
缓存管理器:实现缓存空间定义,自定义缓存目录(支持自动创建多级目录),无需每次都使用S或者Cache::getInstance()重新设定参数。

1.MyCache.class.php
路径:项目目录/Lib/ORG/MyCache.class.php
缓存管理器类,在该类中通过$_tags数组定义每一个缓存空间。例如:将栏目相关的缓存都放在 /runtime/cache/type/ 下,只需要在在该类构造函数中定义:$this->_tags=array(
    'type'=>array('temp'=>CACHE_PATH.'type/'),
);
每行定义一个缓存空间,这里定义了一个名为type的缓存空间,缓存文件统一保存在 /runtime/cache/type/目录中。

2.公共函数MyCache()
该函数添加到common.php中,在任意地方通过MyCache('type')->set('typelist',$arr);直接可以在type缓存空间中设置一个名为typelist的缓存变量。当然,如果需要重复调用,你可以$cache=MyCache('type');
$cache->set('typelist',$arr);
$cache->get('typelist');
你可以删除一个缓存通过$cache->rm('typelist');你可以清空缓存空间内的所有缓存$cache->clear();下面贴出代码:
Common/common.php/**
 * 缓存管理实例化
 */
function MyCache($tag){
    import("ORG.MyCache",LIB_PATH);
    $cache=MyCache::getInstance();
    if(!$cache->choosetag($tag)){
        echo $cache->getLastError();
        return false;
    }
    return $cache;
}
/Lib/ORG/MyCache.class.php<?php
/**
 * 缓存管理器
 */
class MyCache {
    private $CacheOBJ;//Cache核心类实例,单例
    public $_tags=array();//缓存标签定义
    public $errors=array();//错误
    private function __construct() {
        if(!($this->CacheOBJ instanceof Cache)){
            $this->CacheOBJ=Cache::getInstance();
        }
        $this->_tags=array(
            "Type"=>array("temp"=>CACHE_PATH.'Type/','expire'=>'3600')
        );
    }
    //静态方法,用于获取缓存管理器实例
    static function getInstance(){
        static $mycache;
        if(!is_object($mycache) || !($mycache instanceof self)){
            $mycache=new self();
        }
        return $mycache;
    }
    
    
    function choosetag($tag=""){
        if(!empty($tag) && !isset($this->_tags[$tag])){
            $this->errors[]="未找到指定的{$tag}缓存空间!";
            return FALSE;
        }
        $options = $this->_tags[$tag];
        if (isset($options['temp']) && !is_dir($options['temp'])) {
            if (!mkdir($options['temp'], "0777", true)) {
                $this->errors[]="创建缓存目录{$options['temp']}失败,请检查PHP权限或者手动创建";
                return false;
            }
        }
        foreach ($options as $k => $v) {
            $this->CacheOBJ->setOptions($k, $v);
        }
        return true;
    }
    
    function getLastError(){
        return array_pop($this->errors);
    }
    
    //智能设定缓存空间参数
    function __call($method, $arguments) {
        return call_user_func_array(array($this->CacheOBJ,$method), $arguments);
    }
}
最佳答案
评论( 相关
后面还有条评论,点击查看>>