mk4u / cache
一个简单的缓存库。
v0.2.3
2024-08-25 21:24 UTC
Requires
- psr/simple-cache: ^3.0
Requires (Dev)
- symfony/var-dumper: ^7.1
README
PHP的简单灵活的缓存系统。
特性
- 支持多种缓存驱动程序(APCu和文件)
- 实现了
Psr\SimpleCache\CacheInterface
接口。 - 高效的数据存储和检索。
要求
- PHP 8.2或更高版本
- APCu扩展(可选)
安装
composer require mk4u/cache
使用方法。
配置
要使用该库,您必须首先创建您想要使用的缓存驱动程序的实例。该库包括一个Mk4U\Cache\CacheFactory
,它可以轻松地创建缓存驱动程序的实例。
提示
如果没有向Mk4U\Cache\CacheFactory::create()
传递任何参数,则默认将创建一个Mk4U\Cache\Drivers\File
类型的对象。
注意
默认情况下,Mk4U\Cache\Drivers\File
对象设置了以下配置参数
[ //缓存文件的扩展名 'ext' =>'cache', //缓存存储的目录,如果不存在则创建它。 'dir' => dirname(DIR, 4) . '/cache', //缓存生存时间(默认5分钟。) 'ttl' => 300 ]
使用Mk4U\Cache\Drivers\File
驱动程序的示例
require 'vendor/autoload.php'; // Cache driver configuration $config = [ 'ext' => 'txt', // Extension of cache files. 'dir' => __DIR__ . '/cache', // Directory where the cache will be stored 'ttl' => 3600 // Cache lifetime in seconds. ]; // Create an instance of the file cache driver. $cache = Mk4U\Cache\CacheFactory::create('file', $config);
重要
确保您设置了创建目录和缓存文件的必要权限。
使用Mk4U\Cache\Drivers\Apcu
驱动程序的示例
require 'vendor/autoload.php'; // Cache driver configuration $config = [ 'ttl' => 3600 // cache lifetime in seconds (default 5 minutes.) ]; // Create an instance of the APCu cache driver. $cache = Mk4U\Cache\CacheFactory::create('apcu', $config);
Mk4U\Cache\Drivers\Apcu
只有一个可配置的参数,即ttl
,默认值为300秒(5分钟)。
可用方法
缓存类实现了CacheInterface接口的以下方法
get(string $key, mixed $default = null): mixed
set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool
delete(string $key): bool
clear(): bool
getMultiple(iterable $keys, mixed $default = null): iterable
setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool
deleteMultiple(iterable $keys): bool
has(string $key): bool
方法使用示例
将值存储到缓存中
// Store the value in the cache $cache->set('my_key', 'Hello, World!');
从缓存中检索值
// Retrieve cache value $cachedValue = $cache->get('my_key', 'Default value'); echo $cachedValue; // Print: Hello, World!
从缓存中删除值
// Delete the value from the cache $cache->delete('my_key');
通过其键检查值是否存在于缓存中
// checks if a value exists return $cache->has('my_key'); //false
清除整个缓存
// Clear the entire cache $cache->clear();
处理多个值
您可以使用setMultiple、getMultiple和deleteMultiple方法存储、检索和删除多个值。
存储多个值
$values = [ 'key1' => 'Value 1', 'key2' => 'Value 2' ]; $cache->setMultiple($values);
检索多个值
$keys = ['key1', 'key2']; $cachedValues = $cache->getMultiple($keys, 'Default value'); print_r($cachedValues); // Print stored values
删除多个值
$keysToDelete = ['key1', 'key2']; $cache->deleteMultiple($keysToDelete);
异常
该库抛出以下异常
Mk4U\Cache\Exceptions\CacheException
:对于与缓存相关的错误。Mk4U\Cache\Exceptions\InvalidArgumentException
:对于无效的参数。
贡献
欢迎贡献。如果您希望做出贡献,请在存储库中打开一个问题或拉取请求。
许可
本项目采用MIT许可证。
联系方式
如果您有任何问题或评论,请随时通过http://t.me/alexsadrov16联系我