camoo/cache

缓存系统库

安装次数: 1,459

依赖者: 2

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

开放问题: 0

类型:camoo-plugin

2.3.1 2024-04-23 13:29 UTC

This package is auto-updated.

Last update: 2024-09-23 14:22:07 UTC


README

PHP的灵活缓存库,支持文件系统存储和Redis存储选项,可选加密功能。

安装

通过Composer安装此包

composer require camoo/cache

配置

在使用Camoo Cache之前,您需要根据您的缓存策略和安全偏好进行配置。

生成加密盐(可选)

为了加密,生成一个随机的加密盐并安全保存,例如,在环境变量中

use Defuse\Crypto\Key;

$key = Key::createNewRandomKey();
$salt = $key->saveToAsciiSafeString();

基本用法

导入和配置缓存系统,然后读取和写入数据

use Camoo\Cache\Cache;
use Camoo\Cache\CacheConfig;

// Configuration for using FileSystem with encryption
$config = CacheConfig::fromArray([
    'duration' => 3600, // Cache duration in seconds
    'crypto_salt' => $salt, // Use the generated salt for encryption
    'encrypt' => true, // Enable encryption
]);

// Configuration for using FileSystem without encryption
$configNoEncrypt = CacheConfig::fromArray([
    'duration' => '+2 weeks', // Relative format supported
    'encrypt' => false,
]);

$cache = new Cache($config);

// Writing data to the cache
$cache->write('foo', 'bar');

// Reading data from the cache
$value = $cache->read('foo');

使用Redis作为缓存后端

要使用Redis,将RedisEngine指定为类名,并提供Redis特定的配置

$configRedis = CacheConfig::fromArray([
    'className' => \Camoo\Cache\RedisEngine::class, // Specify Redis engine
    'duration' => 3600, // TTL for cache entries
    'crypto_salt' => $salt, // Optional: for encrypted cache
    'encrypt' => true, // Enable encryption
    'server' => '127.0.0.1', // Redis server address
    'port' => 6379, // Redis server port
    'password' => 'foobar', // Redis password if required
    'database' => 0 // Redis database index
]);

$cacheRedis = new Cache($configRedis);

// Writing data to Redis
$cacheRedis->write('foo', 'data');

// Reading data from Redis
$data = $cacheRedis->read('foo');

高级配置

Camoo Cache可以定制各种设置,包括命名空间管理、键前缀和调整底层适配器的选项。有关更多详细信息,请参阅\Camoo\Cache\CacheConfig类中的完整配置选项。