lithemod/cache

使用文件系统的缓存机制。

v1.0.0 2024-10-02 10:55 UTC

This package is auto-updated.

Last update: 2024-10-02 10:56:55 UTC


README

此模块提供了一个简单的使用文件系统的缓存机制。

安装

要安装 lithemod/cache 模块,您可以使用 Composer。在您的项目根目录中运行以下命令

composer require lithemod/cache

使用方法

安装后,您可以使用 Cache 类来存储和检索缓存数据。以下是如何设置和使用缓存的示例

1. 配置缓存目录

在使用缓存之前,您必须定义存储缓存数据的目录。您可以通过调用 Cache 类的 dir 方法来完成此操作

use Lithe\Support\Cache;

// Define the cache directory
Cache::dir(__DIR__ . '/cache');

2. 存储数据到缓存

要将数据存储到缓存中,请使用 add 方法。您可以指定键、要存储的数据、过期时间和要使用的序列化器

// Add data to the cache
Cache::add('my_data', ['foo' => 'bar'], 3600, 'serialize');

3. 从缓存中检索数据

要从缓存中检索存储的数据,请使用 get 方法

// Retrieve data from the cache
$data = Cache::get('my_data');

if ($data === null) {
    echo "Data not found or expired.";
} else {
    print_r($data);
}

4. 使缓存数据无效

如果您需要从缓存中删除数据,请使用 invalidate 方法

// Invalidate the cached data
Cache::invalidate('my_data');

5. 使用 remember

您还可以使用 remember 方法来缓存数据或执行回调以检索缓存中未找到的新数据

$data = Cache::remember('my_key', function () {
    // Logic to fetch data if not in cache
    return ['foo' => 'bar'];
}, 3600, 'serialize');

print_r($data);

可用方法

  • Cache::dir($dir): 设置缓存目录。
  • Cache::add($key, $data, $expiration, $serializer): 将数据存储到缓存中。
  • Cache::get($key): 从缓存中检索数据。
  • Cache::invalidate($key): 从缓存中删除数据。
  • Cache::remember($key, $callback, $expiration, $serializer): 从缓存中检索数据或执行回调以获取和存储新数据。

最后考虑

确保缓存目录具有适当的写入权限,以避免访问问题。此模块是缓存的一个简单解决方案,可用于各种 PHP 应用程序。