PHP code example of asfop / cache-kv
1. Go to this page and download the library: Download asfop/cache-kv library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
asfop / cache-kv example snippets
// 一行代码搞定:检查缓存 → 未命中则获取数据 → 自动回填缓存
$data = kv_get('user.profile', ['id' => 123], function() {
return getUserFromDatabase(123); // 只在缓存未命中时执行
});
Asfop\CacheKV\Core\CacheKVFactory;
// 配置Redis连接
CacheKVFactory::configure(function() {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
return $redis;
});
// 单个数据获取
$user = kv_get('user.profile', ['id' => 123], function() {
return ['id' => 123, 'name' => 'John', 'email' => '[email protected] '];
});
// 批量数据获取
$users = kv_get_multi('user.profile', [
['id' => 1], ['id' => 2], ['id' => 3]
], function($missedKeys) {
$data = [];
foreach ($missedKeys as $cacheKey) {
$keyString = (string)$cacheKey;
$params = $cacheKey->getParams();
$data[$keyString] = getUserFromDatabase($params['id']);
}
return $data; // 返回关联数组
});
// 批量获取键对象(不执行缓存操作)
$keys = kv_get_keys('user.profile', [
['id' => 1], ['id' => 2], ['id' => 3]
]);
// 检查键配置
foreach ($keys as $keyString => $keyObj) {
echo "键: {$keyString}, 有缓存配置: " . ($keyObj->hasCacheConfig() ? '是' : '否') . "\n";
}
// 获取统计信息
$stats = kv_stats();
// ['hits' => 1500, 'misses' => 300, 'hit_rate' => '83.33%', ...]
// 获取热点键
$hotKeys = kv_hot_keys(10);
// ['user:profile:123' => 45, 'user:profile:456' => 32, ...]
// 清空统计数据
kv_clear_stats();
kv_get($template, $params, $callback, $ttl) // 获取缓存
kv_get_multi($template, $paramsList, $callback) // 批量获取
kv_key($template, $params) // 创建键字符串
kv_keys($template, $paramsList) // 批量创建键
kv_get_keys($template, $paramsList) // 获取键对象
kv_delete($template, $params) // 删除指定缓存
kv_delete_prefix($template, $params) // 按前缀删除
kv_delete_full($prefix) // 按完整前缀删除
kv_stats() // 获取统计信息
kv_hot_keys($limit) // 获取热点键
kv_clear_stats() // 清空统计
kv_config() // 获取配置对象(可转换为数组)