mrmanchot/simple-cache

此包最新版本(1.2.7)的许可证信息不可用。

一个简单高效的PHP缓存管理库。

1.2.7 2024-09-25 12:45 UTC

This package is auto-updated.

Last update: 2024-09-25 12:51:50 UTC


README

SimpleCache 是一个轻量级且高效的 PHP 缓存库,旨在易于使用和灵活。无论是缓存字符串、数组、对象还是布尔值,SimpleCache 都提供直观的 API,以加快您的 PHP 应用程序。具有缓存过期、子目录组织和安全措施等特性,它是小型项目和大型应用的最佳解决方案。

特性

  • 易于使用
  • 支持多种数据类型:字符串、数组、对象和布尔值
  • 允许设置缓存过期时间
  • 可选绕过缓存
  • 对缓存键进行清理以确保安全性
  • 优雅的错误处理,使用警告而不是异常

安装

使用 Composer 安装此库

composer require mrmanchot/simple-cache

使用方法

初始化

use Mrmanchot\SimpleCache\SimpleCache;
require 'vendor/autoload.php';

$cache = new SimpleCache('/path/to/cache/directory/');

基本使用

// Set cache
$cache->set('key', 'value');

// Get cache
$value = $cache->get('key');

使用过期时间

您可以使用 $delayMinutes 参数指定分钟数作为过期时间。

// Set cache
$cache->set('key', 'value');

// Get cache, valid for 10 minutes
$value = $cache->get('key', 10);

存储数组、对象和布尔值

您还可以存储数组、对象和布尔值。

// Storing an array
$cache->set('array_key', ['a' => 1, 'b' => 2]);

// Retrieving an array
$array = $cache->get('array_key');

// Storing an object
$object = new stdClass();
$object->property = 'value';
$cache->set('object_key', $object);

// Retrieving an object
$object = $cache->get('object_key');

// Storing a boolean
$cache->set('boolean_key', true);

// Retrieving a boolean
$boolean = $cache->get('boolean_key');

处理缓存命中和未命中

在从缓存检索数据时,您可以通过检查返回的值是否为 null 来区分缓存命中和未命中。如果值为 null,表示数据不在缓存中(未命中),您可能需要计算或生成该值。如果值不为 null,则表示缓存命中,您可以直接使用缓存的值。

以下是如何处理缓存命中和未命中的示例

$cachedValue = $cache->get('some_key');
if ($cachedValue === null) {
    // The value is not in the cache, compute/generate the value
}

使用子目录作为键

您可以使用键中的子目录进行更好的组织。请注意,出于安全目的,键将进行清理,因此只允许某些字符。

// Set cache in a subdirectory
$cache->set('user/1', 'value');

// Get cache from a subdirectory
$value = $cache->get('user/1');

清除缓存

clear 方法允许您根据模式删除缓存项。这对于批量无效化缓存项很有用。

// Clear a specific cache item
$cache->clear('key');

// Clear all cache items in a subdirectory
$cache->clear('user/*');

// Clear all cache items
$cache->clear('*');

运行 PHPUnit

phpunit test/SimpleCacheTest.php