kminek/cache

史上最简单的缓存实现!

v2.0.0 2018-02-23 17:42 UTC

This package is auto-updated.

Last update: 2024-09-17 08:42:26 UTC


README

这是一个非常简单的文件系统缓存实现,适用于广泛版本的PHP。只需插入即可使用——完美适用于小型项目和快速脚本,在这些项目中您不需要完整的缓存解决方案。

安装

$ composer require kminek/cache

API

/**
 * @param string $key
 * @param mixed  $default
 *
 * @return mixed
 */
function cache_get($key, $default = null);

/**
 * @param string   $key
 * @param mixed    $value
 * @param null|int $ttl
 *
 * @return bool
 */
function cache_set($key, $value, $ttl = null);

/**
 * @param string $key
 *
 * @return bool
 */
function cache_delete($key);

/**
 * @return bool
 */
function cache_clear();

使用

require 'vendor/autoload.php';

$cachedData = cache_get('cachedData');

if (!$cachedData) {
    echo 'Saving cache...' . PHP_EOL;
    cache_set('cachedData', array('lorem', 'ipsum'), 5 * 60); // 5 minutes
} else {
    echo 'Data retrieved from cache!' . PHP_EOL;
    var_dump($cachedData);
}

高级使用

// set your custom configuration options (below are default ones)
Kminek_Cache::configure(array(
    'engine' => Kminek_Cache::ENGINE_SERIALIZE, // or Kminek_Cache::ENGINE_JSON or Kminek_Cache::ENGINE_VAR_EXPORT
    'dir' => sys_get_temp_dir(), // where to store cache files
    'prefix' => 'kminek_cache',
    'separator' => '_',
    'extension' => '.cache',
    'ttl' => 60 * 60, // default ttl in seconds (1 hour)
));

// then use cache as you would normally do
$cachedData = cache_get('cachedData');
...