gokhankurtulus/jsoncache

一个简单的PHP缓存库。

1.0.2 2023-07-10 21:17 UTC

This package is auto-updated.

Last update: 2024-09-22 03:22:30 UTC


README

License: MIT PHP Version Release

JsonCache是一个简单的PHP库,它提供了一个简单的数据缓存机制。它通过采用基于文件的存储方法,使得JSON数据的存储和检索变得高效。

安装

您可以使用Composer安装此库。运行以下命令

composer require gokhankurtulus/jsoncache

用法

初始化

要开始使用JsonCache,您需要创建一个JsonCache类的实例。您可以传递一个可选的配置数组来自定义缓存行为。

use JsonCache\JsonCache;

$config = [
    'storage_path' => '/path/to/storage',
    'index_file' => 'index.json',
    'lifetime' => 60, // seconds
    'force_create_storage_path' => true,
    'force_create_index_file' => true,
    'json_flags' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
    'compress' => true
];

$jsonCache = new JsonCache($config);

缓存数据

您可以使用set方法存储JSON数据。提供唯一键和您要缓存的数据。

$jsonCache->set('my_key', ['name' => 'John Doe', 'age' => 30]);

检索数据

要检索缓存中的数据,使用get方法并提供键,默认情况下它返回数组。

$data = $jsonCache->get('my_key');
if ($data !== null) {
    // Use the cached data
    echo $data['name']; // John Doe
    echo $data['age']; // 30
} else {
    // Data not found or expired
}

检查存在性

您可以使用has方法检查键是否存在于缓存中。

if ($jsonCache->has('my_key')) {
    // Key exists in the cache
} else {
    // Key does not exist
}

删除数据

要从一个缓存中删除键,请使用delete方法。

$jsonCache->delete('my_key');

清除缓存

要清除缓存,请使用clear方法。

$jsonCache->clear();

方法

在创建JsonCache实例后,您也可以使用这些方法。

$jsonCache->getCacheSize('my_key'); // Returns the size of the key in bytes
$jsonCache->getLifetime(); // Returns cache instance lifetime
$jsonCache->setLifetime(120); // Sets cache instance lifetime to 120 seconds
$jsonCache->isCompressed(); // Returns cache compress status
$jsonCache->getConfig(); // Returns config array
$jsonCache->getStoragePath(); // Returns config's storage path
$jsonCache->getIndexFile(); // Returns config's index file path
$jsonCache->getJsonFlags(); // Returns config's json flags

许可协议

JsonCache是一个开源软件,在MIT许可协议下发布。您可以在项目中自由修改和使用它。

贡献

欢迎为JsonCache做出贡献!如果您发现任何问题或对改进有建议,请创建问题或在GitHub仓库上提交拉取请求。