使用缓存

优质
小牛编辑
133浏览
2023-12-01

classpath : herosphp\cache\CacheFactory

herophp的缓存是通过缓存工厂来管理的,CacheFactory 负责创建缓存,默认采用的是单例模式,也就是同一类型的缓存在应用中只会存再一个实例。

$cacher = CacheFactory::create('file', true);

我们为缓存工具定义了一个 ICache接口,它定义了以下接口方法:

get($key)

获取缓存

参数名称参数类型参数说明
$keystring缓存的位置标志key

set($key, $content, $expire)

添加或者更新缓存

参数名称参数类型参数说明
$keystring缓存的位置标志key
$contentstring|array缓存内容
$expireint缓存的有效期,单位是秒

delete($key)

删除缓存

参数名称参数类型参数说明
$keystring缓存的位置标志key

文件缓存

文件缓存比较棘手的问题是缓存的分类,因为一个文件的inode节点是有限的,如果不分类存储的话,一下就突破了inode节点了。所以文件缓存我们提供了额外的三个API

baseKey( $baseKey )

参数名称参数类型参数说明
$baseKeystring缓存的基础路径,最好有语义,推荐使用action名称, 如article

ftype( $ftype = null )

参数名称参数类型参数说明
$ftypestring缓存分类目录, 推荐使用当前调用的method操作,
如 index,list,detail等

factor( $factor = null )

参数名称参数类型参数说明
$factorstring缓存的分类因子,一般来说,
如果是列表页,推荐使用页码$page;
如果是详情页,推荐使用$id

这里需要说明的是,如果你调用了 factor() 方法, 那么你再调用 ICache::get()方法的时候就不用再传入 $key 参数了,因为 $factor 已经可以帮你定位到缓存文件了。

$CACHER = CacheFactory::create('file');
$CACHER->baseKey('article')->ftype('list')->factor(1);
$data = $CACHER->get(null);

if ( $data == false ) {
    $model = Loader::model("article");
    $data = $model->getItems(null, null, array('id' => -1), array(0, 20));

    $CACHER->set(null, $data, 3600);
}

memcache缓存

使用memcache之前你需要先去 配置缓存

使用起来非常简单

$helper = CacheFactory::create("memo");
$key = 'test.data';
$data = $CACHER->get($key);
if ( !$data ) {
    $CACHER->set($key, "测试 Memcache 缓存数据!");
}

redis缓存

使用redis缓存之前,你同样需要先 配置缓存

然后直接使用:

$CACHER = CacheFactory::create('redis');
$CACHER->set("test_key", "this is the test data", 10);

var_dump($CACHER->get("test_key"));