PHP code example of f-oris / easy-cache
1. Go to this page and download the library: Download f-oris/easy-cache 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/ */
f-oris / easy-cache example snippets
use Foris\Easy\Cache\Cache;
$config = [
// 缓存配置
];
$cache = new Cache($config);
/**
* 设置单个缓存
*
* 注:set方法等同于put方法
*/
$cache->set('key', 'value');
$cache->put('key', 'value', 3600);
/**
* 设置多个缓存
*
* 注:等价于调用了多次put,分别设置key_1,key_2,缓存时间为3600秒
*/
$cache->putMany(['key_1' => 'value_1', 'key_2' => 'value_2'], 3600);
use Foris\Easy\Cache\Cache;
$config = [
// 缓存配置
];
$cache = new Cache($config);
/**
* 缓存存在时,返回true, 不存在时,返回false.
*/
$cache->has('key');
use Foris\Easy\Cache\Cache;
$config = [
// 缓存配置
];
$cache = new Cache($config);
/**
* 获取缓存结果
*
* 注:获取不到缓存的情况下,返回null
*/
$cache->get('key');
use Foris\Easy\Cache\Cache;
$config = [
// 缓存配置
];
$cache = new Cache($config);
/**
* 通过闭包函数设置缓存
*
* 注:
* 1. 等价于将闭包函数的运行结果缓存到key中,缓存时间为3600秒
* 2. 缓存没命中的情况下,会执行闭包函数,写入缓存,并返回执行结果,缓存命中的情况下,直接返回缓存结果
*/
$cache->remember('key', 3600, function () {
return 'value';
});
use Foris\Easy\Cache\Cache;
$config = [
// 缓存配置
];
$cache = new Cache($config);
/**
* 删除指定缓存
*
* 注:forget等价于delete
*/
$cache->forget('key');
$cache->delete('key');
/**
* 清除所有缓存
*
* 注:flush等价于clear
*/
$cache->flush();
$cache->clear();
class MyFilesystemAdapter extends \Symfony\Component\Cache\Adapter\FilesystemAdapter
{
}
$callback = function (array $config = []) {
return new MyFilesystemAdapter($config['namespace'], $config['lifetime'], $config['path']);
};
$factory = new \Foris\Easy\Cache\Factory();
$factory->extend($callback, 'my-file');
$config = [
// ...
'drivers' => [
// ...
'my-file' => [
'namespace' => 'my_file',
'lifetime' => 1800,
'path' => sys_get_temp_dir() . '/my-cache/',
]
]
];
$cache = new \Foris\Easy\Cache\Cache($factory, $config);
$cache->driver('my-file')->set('key', 'value');