PHP code example of kode / cache

1. Go to this page and download the library: Download kode/cache library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kode / cache example snippets


use Kode\Cache\CacheManager;

// 创建缓存管理器
$cache = new CacheManager([
    'default' => 'file',
    'path' => '/tmp/cache',
    'prefix' => 'app:',
    'expire' => 3600,
]);

// 设置缓存
$cache->set('key', 'value', 3600);

// 获取缓存
$value = $cache->get('key', 'default');

// 判断存在
if ($cache->has('key')) {
    // ...
}

// 删除缓存
$cache->delete('key');

// 获取并删除
$value = $cache->pull('key');

// 自动获取/设置
$value = $cache->remember('key', function() {
    return expensive_computation();
}, 3600);

use Kode\Cache\Facade as Cache;

// 设置
Cache::set('name', 'value', 3600);

// 获取
$name = Cache::get('name', 'default');

// 删除
Cache::delete('name');

// 自增/自减
Cache::set('counter', 0);
Cache::increment('counter');
Cache::decrement('counter', 5);

// 永久缓存
Cache::forever('user_avatar', $avatarUrl);

// 清除所有
Cache::flush();

$cache = new CacheManager([
    'default' => 'file',
    'path' => '/tmp/kode_cache',     // 缓存目录
    'prefix' => 'app:',               // 缓存前缀
    'expire' => 3600,                // 默认过期时间 (秒)
    'subDir' => true,                 // 是否使用子目录 (减少单目录文件数)
    'hashType' => 'md5',             // 哈希算法: md5/sha1/xxh3
]);

$cache = new CacheManager([
    'default' => 'memory',
    'prefix' => 'mem:',
    'expire' => 0,
]);

$cache = new CacheManager([
    'default' => 'redis',
    'host' => '127.0.0.1',
    'port' => 6379,
    'password' => null,               // Redis 密码
    'database' => 0,                  // 数据库编号
    'prefix' => 'kode:',              // 缓存前缀
    'expire' => 3600,                 // 默认过期时间
    'timeout' => 0.0,                // 连接超时
    'persistent' => null,             // 持久化连接 ID
]);

$cache = new CacheManager([
    'default' => 'memcached',
    'memcached_host' => '127.0.0.1',
    'memcached_port' => 11211,
    'memcached_username' => null,    // SASL 用户名
    'memcached_password' => null,    // SASL 密码
    'prefix' => 'kode:',
    'expire' => 3600,
]);

$cache = new CacheManager([
    'default' => 'apcu',
    'prefix' => 'kode:',
    'expire' => 3600,
]);

$cache = new CacheManager([
    'default' => 'sqlite',
    'sqlite_path' => '/tmp/cache.sqlite',  // 数据库文件路径
    'prefix' => 'kode:',
    'expire' => 3600,
]);

$cache = new CacheManager([
    'default' => 'file',
    'stores' => [
        'file' => [
            'type' => 'file',
            'path' => '/tmp/cache',
            'prefix' => 'app:',
        ],
        'redis' => [
            'type' => 'redis',
            'host' => '127.0.0.1',
            'port' => 6379,
        ],
        'memory' => [
            'type' => 'memory',
        ],
        'memcached' => [
            'type' => 'memcached',
            'host' => '127.0.0.1',
            'port' => 11211,
        ],
        'apcu' => [
            'type' => 'apcu',
        ],
        'sqlite' => [
            'type' => 'sqlite',
            'path' => '/tmp/cache.sqlite',
        ],
    ],
]);

// 使用不同驱动
$cache->store('file')->set('key', 'value');
$cache->store('redis')->set('key', 'value');
$cache->store('memory')->set('key', 'value');
$cache->store('apcu')->set('key', 'value');

// 默认驱动
$cache->get('key');

use Kode\Cache\Contract\StoreInterface;
use Kode\Cache\Store\AbstractStore;

class MyCustomStore extends AbstractStore
{
    protected function getItem(string $key): ?array
    {
        // 实现获取逻辑
        $value = some_storage_get($key);
        return $value !== null ? ['value' => $value, 'expire' => 0] : null;
    }

    protected function setItem(string $key, mixed $value, int $expire): bool
    {
        // 实现设置逻辑
        return some_storage_set($key, $value, $expire);
    }

    protected function deleteItem(string $key): bool
    {
        // 实现删除逻辑
        return some_storage_delete($key);
    }

    protected function clearAll(): bool
    {
        // 实现清空逻辑
        return some_storage_clear();
    }
}

use Kode\Cache\CacheManager;

// 注册自定义驱动
CacheManager::extend('custom', MyCustomStore::class);

// 使用自定义驱动
$cache = new CacheManager([
    'default' => 'custom',
]);

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

// 设置缓存
$cache->set('key', 'value', 3600);           // 3600 秒后过期
$cache->set('key', 'value');                  // 使用默认过期时间
$cache->put('key', 'value', 3600);           // 显式指定过期时间

// 获取缓存
$value = $cache->get('key');
$value = $cache->get('key', 'default');      // 不存在时返回默认值

// 检查存在
$exists = $cache->has('key');

// 删除缓存
$cache->delete('key');

// 获取并删除
$value = $cache->pull('key');

// 批量获取
$values = $cache->many(['key1', 'key2', 'key3'], 'default');
$values = $cache->getMultiple(['key1', 'key2', 'key3'], 'default');

// 批量设置
$cache->putMany(['key1' => 'value1', 'key2' => 'value2'], 3600);
$cache->setMultiple(['key1' => 'value1', 'key2' => 'value2'], 3600);

// 批量删除
$cache->deleteMultiple(['key1', 'key2']);

$cache->set('counter', 0);
$cache->increment('counter');      // +1
$cache->increment('counter', 5); // +5
$cache->decrement('counter');     // -1
$cache->decrement('counter', 3);  // -3

// 如果不存在则设置并返回
$value = $cache->remember('key', function() {
    return expensive_computation();
}, 3600);

// 永久缓存
$value = $cache->rememberForever('key', function() {
    return compute_once();
});

// 仅当键不存在时设置成功
$result = $cache->store()->add('key', 'value', 3600);

// 创建标签
$tag = $cache->tag('products');

// 设置带标签的缓存
$tag->set('product_1', $product1);
$tag->set('product_2', $product2);

// 获取
$product = $tag->get('product_1');

// 判断
if ($tag->has('product_1')) {
    // ...
}

// 删除单个
$tag->delete('product_1');

// 清除标签下所有缓存
$tag->clear();

// 多个标签
$tag = $cache->tag(['user', 'vip']);
$tag->set('user_1', $userData);

// 获取标签下的所有键
$keys = $tag->getTagItems();

use Kode\Cache\CacheItem;

$item = CacheItem::create('key')
    ->set($value)
    ->setTtl(3600);

$cache->set('key', $item->get(), $item->getTtl());

// 使用 DateInterval
$item->expiresAfter(new \DateInterval('PT1H'));

// 设置绝对过期时间
$item->expiresAt(time() + 3600);

// 检查是否过期
if ($item->isExpired()) {
    // ...
}

// 转换为数组
$array = $item->toArray();

use Kode\Cache\Serializer\PhpSerializer;       // PHP 原生序列化 (默认)
use Kode\Cache\Serializer\JsonSerializer;     // JSON 序列化
use Kode\Cache\Serializer\IgBinarySerializer; // igbinary 扩展 (最高效)

// 检查可用性
if (\Kode\Cache\Serializer\SerializerFactory::isAvailable('igbinary')) {
    $serializer = \Kode\Cache\Serializer\SerializerFactory::create('igbinary');
}

// JSON 序列化器可配置
$jsonSerializer = new JsonSerializer(
    assoc: true,   // 返回关联数组
    depth: 512,    // 最大深度
    options: 0     // JSON 选项 (如 JSON_UNESCAPED_UNICODE)
);

use Kode\Cache\DistributedLock;

// 创建分布式锁 (需要 Redis 驱动)
$redisStore = new \Kode\Cache\Store\RedisStore('127.0.0.1', 6379);
$lock = new DistributedLock($redisStore, 'resource_lock', 10);

// 获取锁
if ($lock->acquire()) {
    try {
        // 临界区操作
        do_something();
    } finally {
        $lock->release();
    }
}

// 阻塞获取锁 (最多等待 5 秒)
$lock = new DistributedLock($redisStore, 'blocking_lock', 10);
if ($lock->block(5)) {
    try {
        do_something();
    } finally {
        $lock->release();
    }
}

// 锁延期 (延长锁的持有时间)
$lock->extend(30);

// 检查锁是否被持有
if ($lock->isOwned()) {
    // ...
}

use Kode\Cache\Lock;

$store = $cache->store();
$lock = new Lock($store, 'local_lock', 10);

if ($lock->acquire()) {
    try {
        do_something();
    } finally {
        $lock->release();
    }
}

// 阻塞获取
if ($lock->block(5)) {
    // ...
}

use Kode\Cache\CoLock;

// 创建协程锁
$lock = new CoLock('coroutine_lock', 10); // 10秒超时

// 获取锁(非阻塞)
if ($lock->acquire()) {
    try {
        // 临界区操作
        do_something();
    } finally {
        $lock->release();
    }
}

// 阻塞获取锁(等待最多 5 秒)
$lock = new CoLock('blocking_lock');
if ($lock->block(5)) {
    try {
        do_something();
    } finally {
        $lock->release();
    }
}

// 检查锁是否被持有
if ($lock->isOwned()) {
    // ...
}

// 锁延期
$lock->extend(30);

// 设置上下文管理器(可选,用于协程间协调)
use Kode\Cache\CoLock;
CoLock::setContext(\Kode\Context::class);

// 重置上下文
CoLock::resetContext();

use Kode\Cache\AtomicCounter;

$redisStore = new \Kode\Cache\Store\RedisStore('127.0.0.1', 6379);
$counter = new AtomicCounter($redisStore, 'page_views');

// 自增/自减
$counter->increment();        // +1
$counter->increment(10);     // +10
$counter->decrement();       // -1
$counter->decrement(5);      // -5

// 获取当前值
$views = $counter->get();

// 重置
$counter->reset();

use Kode\Cache\RedisPoolManager;

// 创建连接池
$pool = RedisPoolManager::make('127.0.0.1', 6379, null, 0, [
    'min_connections' => 1,
    'max_connections' => 10,
    'idle_timeout' => 60,
    'wait_timeout' => 5,
]);

// 获取连接
$redis = $pool->getConnection();
try {
    $redis->set('key', 'value');
    $value = $redis->get('key');
} finally {
    $pool->releaseConnection($redis);
}

// 获取连接池状态
$status = $pool->getStatus();

// 关闭连接池
$pool->close();

use Kode\Cache\RateLimiter;

$redisStore = new \Kode\Cache\Store\RedisStore('127.0.0.1', 6379);
$limiter = new RateLimiter($redisStore, 'api_limit', 100, 60); // 60 秒内最多 100 次

// 检查是否超限
if ($limiter->tooManyAttempts('user:123')) {
    $retryAfter = $limiter->retryAfter('user:123');
    throw new \Exception("请 {$retryAfter} 秒后重试");
}

// 记录请求
$limiter->hit('user:123');

// 获取剩余次数
$remaining = $limiter->remaining('user:123');

// 获取已用次数
$attempts = $limiter->attempts('user:123');

// 重置
$limiter->clear('user:123');

use Kode\Cache\Config;

// 设置配置
Config::set('cache.driver', 'redis');
Config::set('cache.prefix', 'app:');

// 获取配置
$driver = Config::get('cache.driver');
$prefix = Config::get('cache.prefix', 'kode:');

// 检查存在
if (Config::has('cache.driver')) {
    // ...
}

// 批量设置
Config::set([
    'cache.driver' => 'redis',
    'cache.host' => '127.0.0.1',
]);

// 获取所有配置
$all = Config::all();

// 重置
Config::reset();

// 加载配置
Config::load($configArray);

use Kode\Cache\Exception\CacheException;
use Kode\Cache\Exception\InvalidArgumentException;

try {
    $cache->store('nonexistent')->get('key');
} catch (InvalidArgumentException $e) {
    echo "驱动未配置: " . $e->getMessage();
}

try {
    $cache->set('key', $value);
} catch (CacheException $e) {
    echo "缓存操作失败: " . $e->getMessage();
}

use Kode\Cache\CacheManager;

// 方式1: 直接使用
$cache = new CacheManager([
    'default' => 'redis',
    'host' => config('cache.redis.host'),
    'port' => config('cache.redis.port'),
    'password' => config('cache.redis.password'),
]);

// 方式2: 注册为服务 (在 ServiceProvider 中)
Container::getInstance()->bind('cache', function() {
    return new CacheManager([
        'default' => 'redis',
        'host' => config('cache.redis.host'),
        'port' => config('cache.redis.port'),
    ]);
});

// 方式3: Facade
Facade::alias('cache', \Kode\Cache\Facade::class);

use Kode\Cache\Facade as Cache;

// 使用方式与 Laravel Cache 相同
$value = Cache::remember('key', function() {
    return Model::find(1);
}, 3600);

// 直接使用
\CacheManager;

$cache = new CacheManager(['default' => 'file']);
$cache->set('key', 'value', 3600);
bash
./vendor/bin/phpunit tests/FileStoreTest.php