Skip to content

PSR 实现 ​

概述 ​

Kuiper 缓存模块实现了 PSR-6(缓存接口)和 PSR-16(简单缓存接口)标准的接口与方法签名。需要注意:池层与各驱动统一校验键合法性(键按 / 拆分后必须至少包含一个非空分段),非法键抛出 kuiper\cache\stash\InvalidArgumentException——它同时实现 Psr\Cache\InvalidArgumentException 与 Psr\SimpleCache\InvalidArgumentException,并且继承原生 \InvalidArgumentException,三种 catch 写法都能捕获(详见错误处理)。键类型也由同一个校验器处理:PSR-16 的键必须是 string,传入 int / float 等非字符串键同样抛 kuiper\cache\stash\InvalidArgumentException(KeyValidator::normalize()),而不是原生 \InvalidArgumentException。批量方法(getItems() / deleteItems() / getMultiple() / setMultiple())先校验全部键再执行,任一键非法即抛异常,不会部分生效。

PSR-6 缓存接口 ​

PSR-6 定义了缓存池(CacheItemPool)和缓存项(CacheItem)的概念,提供了更丰富和灵活的缓存操作。

核心接口 ​

CacheItemPoolInterface ​

缓存池接口,负责管理缓存项:

php
<?php

declare(strict_types=1);

namespace Psr\Cache;

use Psr\Cache\CacheItemInterface;

interface CacheItemPoolInterface
{
    /**
     * 获取缓存项
     */
    public function getItem(string $key): CacheItemInterface;

    /**
     * 批量获取缓存项
     */
    public function getItems(array $keys = []): iterable;

    /**
     * 检查缓存项是否存在
     */
    public function hasItem(string $key): bool;

    /**
     * 清空缓存池
     */
    public function clear(): bool;

    /**
     * 删除缓存项
     */
    public function deleteItem(string $key): bool;

    /**
     * 批量删除缓存项
     */
    public function deleteItems(array $keys): bool;

    /**
     * 保存缓存项
     */
    public function save(CacheItemInterface $item): bool;

    /**
     * 延迟保存缓存项
     */
    public function saveDeferred(CacheItemInterface $item): bool;

    /**
     * 提交所有延迟保存的缓存项
     */
    public function commit(): bool;
}

CacheItemInterface ​

缓存项接口,表示单个缓存条目:

php
<?php

declare(strict_types=1);

namespace Psr\Cache;

interface CacheItemInterface
{
    /**
     * 获取缓存键
     */
    public function getKey(): string;

    /**
     * 获取缓存值
     */
    public function get(): mixed;

    /**
     * 检查缓存是否命中
     */
    public function isHit(): bool;

    /**
     * 设置缓存值
     */
    public function set(mixed $value): static;

    /**
     * 设置过期时间(相对时间)
     */
    public function expiresAfter(int|\DateInterval|null $time): static;

    /**
     * 设置过期时间(绝对时间)
     */
    public function expiresAt(\DateTimeInterface|null $expiration): static;
}

使用 PSR-6 缓存池 ​

基本使用 ​

php
<?php

declare(strict_types=1);

use kuiper\cache\CacheConfiguration;
use kuiper\di\ContainerBuilder;
use kuiper\helper\Config;
use Psr\Cache\CacheItemPoolInterface;

require __DIR__.'/vendor/autoload.php';

// 获取缓存池
$builder = new ContainerBuilder(
    require __DIR__.'/vendor/autoload.php',
    Config::create([])
);
// 手工构建容器(绕过 Runtime 的自动装配清单)时需显式注册 CacheConfiguration;
// 标准 Runtime 下由 extra.kuiper.configuration 自动注册
$builder->addConfiguration(new CacheConfiguration());
$container = $builder->build();
$cache = $container->get(CacheItemPoolInterface::class);

// 获取缓存项
$item = $cache->getItem('user:123');

// 检查缓存是否命中
if (!$item->isHit()) {
    // 缓存未命中,获取数据并设置缓存
    $user = [
        'id' => 123,
        'name' => 'John Doe',
        'email' => 'john@example.com',
    ];

    $item->set($user);
    $item->expiresAfter(3600); // 1小时后过期
    $cache->save($item);
}

// 获取缓存值
$user = $item->get();
print_r($user);

批量操作 ​

php
<?php

declare(strict_types=1);

use kuiper\cache\CacheConfiguration;
use kuiper\di\ContainerBuilder;
use kuiper\helper\Config;
use Psr\Cache\CacheItemPoolInterface;

$builder = new ContainerBuilder(
    require __DIR__.'/vendor/autoload.php',
    Config::create([])
);
$builder->addConfiguration(new CacheConfiguration());
$container = $builder->build();
$cache = $container->get(CacheItemPoolInterface::class);

// 批量获取缓存项
$keys = ['user:1', 'user:2', 'user:3'];
$items = $cache->getItems($keys);

foreach ($items as $key => $item) {
    if (!$item->isHit()) {
        // 缓存未命中,从数据库获取数据
        $id = (int) explode(':', $key)[1];
        $user = fetchUserFromDatabase($id);

        $item->set($user);
        $item->expiresAfter(3600);
        $cache->save($item);
    }

    echo "User {$key}: {$item->get()['name']}\n";
}

延迟保存 ​

php
<?php

declare(strict_types=1);

use kuiper\cache\CacheConfiguration;
use kuiper\di\ContainerBuilder;
use kuiper\helper\Config;
use Psr\Cache\CacheItemPoolInterface;

$builder = new ContainerBuilder(
    require __DIR__.'/vendor/autoload.php',
    Config::create([])
);
$builder->addConfiguration(new CacheConfiguration());
$container = $builder->build();
$cache = $container->get(CacheItemPoolInterface::class);

// 批量延迟保存
$keys = ['config:db', 'config:cache', 'config:redis'];
foreach ($keys as $key) {
    $item = $cache->getItem($key);
    $config = loadConfig($key);
    $item->set($config);
    $item->expiresAfter(86400); // 24小时

    // 延迟保存,不立即写入
    $cache->saveDeferred($item);
}

// 一次性提交所有延迟保存的项
$cache->commit();

检查缓存是否存在 ​

php
<?php

declare(strict_types=1);

use kuiper\cache\CacheConfiguration;
use kuiper\di\ContainerBuilder;
use kuiper\helper\Config;
use Psr\Cache\CacheItemPoolInterface;

$builder = new ContainerBuilder(
    require __DIR__.'/vendor/autoload.php',
    Config::create([])
);
$builder->addConfiguration(new CacheConfiguration());
$container = $builder->build();
$cache = $container->get(CacheItemPoolInterface::class);

// 检查单个缓存项
if ($cache->hasItem('user:123')) {
    echo "缓存存在\n";
} else {
    echo "缓存不存在\n";
}

// 删除单个缓存项
$cache->deleteItem('user:123');

// 批量删除缓存项
$cache->deleteItems(['user:1', 'user:2', 'user:3']);

// 清空所有缓存
$cache->clear();

TTL 和过期时间 ​

expiresAfter - 相对过期时间 ​

php
<?php

declare(strict_types=1);

use Psr\Cache\CacheItemPoolInterface;

class UserService
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache
    ) {
    }

    public function getUser(int $id): array
    {
        $item = $this->cache->getItem("user:{$id}");

        if (!$item->isHit()) {
            $user = $this->fetchFromDatabase($id);
            $item->set($user);

            // 设置相对过期时间
            $item->expiresAfter(300); // 5分钟后过期
            $this->cache->save($item);
        }

        return $item->get();
    }

    private function fetchFromDatabase(int $id): array
    {
        // 从数据库获取用户
        return [];
    }
}

使用 DateInterval 设置过期时间:

php
<?php

declare(strict_types=1);

use DateInterval;

$item->expiresAfter(new DateInterval('PT1H')); // 1小时
$item->expiresAfter(new DateInterval('P1D'));  // 1天
$item->expiresAfter(new DateInterval('P1W'));  // 1周

expiresAt - 绝对过期时间 ​

php
<?php

declare(strict_types=1);

use DateTime;
use Psr\Cache\CacheItemPoolInterface;

class DailyReportService
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache
    ) {
    }

    public function getReport(string $date): array
    {
        $item = $this->cache->getItem("report:{$date}");

        if (!$item->isHit()) {
            $report = $this->generateReport($date);
            $item->set($report);

            // 设置到今天午夜过期
            $midnight = new DateTime('tomorrow 00:00:00');
            $item->expiresAt($midnight);
            $this->cache->save($item);
        }

        return $item->get();
    }

    private function generateReport(string $date): array
    {
        // 生成日报
        return [];
    }
}

缓存命中和未命中 ​

php
<?php

declare(strict_types=1);

use Psr\Cache\CacheItemPoolInterface;

class CacheService
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache,
        private int $hits = 0,
        private int $misses = 0
    ) {
    }

    public function get(string $key, mixed $default = null): mixed
    {
        $item = $this->cache->getItem($key);

        if ($item->isHit()) {
            ++$this->hits;
            return $item->get();
        }

        ++$this->misses;
        return $default;
    }

    public function getHitRate(): float
    {
        $total = $this->hits + $this->misses;
        return $total > 0 ? $this->hits / $total : 0;
    }
}

PSR-16 简单缓存接口 ​

PSR-16 提供了更简单易用的缓存接口,适合大多数缓存场景。

核心接口 ​

php
<?php

declare(strict_types=1);

namespace Psr\SimpleCache;

interface CacheInterface
{
    /**
     * 获取缓存值
     */
    public function get(string $key, mixed $default = null): mixed;

    /**
     * 设置缓存值
     */
    public function set(string $key, mixed $value, int|\DateInterval|null $ttl = null): bool;

    /**
     * 删除缓存值
     */
    public function delete(string $key): bool;

    /**
     * 清空缓存
     */
    public function clear(): bool;

    /**
     * 批量获取缓存值
     */
    public function getMultiple(iterable $keys, mixed $default = null): iterable;

    /**
     * 批量设置缓存值
     */
    public function setMultiple(iterable $values, int|\DateInterval|null $ttl = null): bool;

    /**
     * 批量删除缓存值
     */
    public function deleteMultiple(iterable $keys): bool;

    /**
     * 检查缓存是否存在
     */
    public function has(string $key): bool;
}

使用 PSR-16 简单缓存 ​

基本使用 ​

php
<?php

declare(strict_types=1);

use kuiper\cache\CacheConfiguration;
use kuiper\di\ContainerBuilder;
use kuiper\helper\Config;
use Psr\SimpleCache\CacheInterface;

require __DIR__.'/vendor/autoload.php';

// 获取简单缓存实例
$builder = new ContainerBuilder(
    require __DIR__.'/vendor/autoload.php',
    Config::create([])
);
$builder->addConfiguration(new CacheConfiguration());
$container = $builder->build();
$cache = $container->get(CacheInterface::class);

// 设置缓存
$user = [
    'id' => 123,
    'name' => 'John Doe',
    'email' => 'john@example.com',
];
$cache->set('user:123', $user, 3600);

// 获取缓存
$user = $cache->get('user:123', ['name' => 'Guest']);
print_r($user);

// 检查缓存是否存在
if ($cache->has('user:123')) {
    echo "缓存存在\n";
}

// 删除缓存
$cache->delete('user:123');

批量操作 ​

php
<?php

declare(strict_types=1);

use kuiper\cache\CacheConfiguration;
use kuiper\di\ContainerBuilder;
use kuiper\helper\Config;
use Psr\SimpleCache\CacheInterface;

$builder = new ContainerBuilder(
    require __DIR__.'/vendor/autoload.php',
    Config::create([])
);
$builder->addConfiguration(new CacheConfiguration());
$container = $builder->build();
$cache = $container->get(CacheInterface::class);

// 批量设置缓存
$users = [
    'user:1' => ['id' => 1, 'name' => 'Alice'],
    'user:2' => ['id' => 2, 'name' => 'Bob'],
    'user:3' => ['id' => 3, 'name' => 'Charlie'],
];
$cache->setMultiple($users, 3600);

// 批量获取缓存
$keys = ['user:1', 'user:2', 'user:3'];
$users = $cache->getMultiple($keys, ['name' => 'Unknown']);
foreach ($users as $key => $user) {
    echo "{$key}: {$user['name']}\n";
}

// 批量删除缓存
$cache->deleteMultiple(['user:1', 'user:2', 'user:3']);

// 清空所有缓存
$cache->clear();

使用 DateInterval 设置 TTL ​

php
<?php

declare(strict_types=1);

use DateInterval;
use Psr\SimpleCache\CacheInterface;

class SessionCache
{
    public function __construct(
        private readonly CacheInterface $cache
    ) {
    }

    public function setSession(string $sessionId, array $data): bool
    {
        // 会话数据 30 分钟后过期
        return $this->cache->set(
            "session:{$sessionId}",
            $data,
            new DateInterval('PT30M')
        );
    }
}

PSR-6 与 PSR-16 对比 ​

特性PSR-6PSR-16
复杂度较高简单
灵活性高中
缓存项有明确对象概念无明确对象概念
延迟保存支持不支持
过期时间相对和绝对相对和绝对
批量操作支持支持
适用场景复杂缓存逻辑简单缓存操作

选择合适的接口 ​

使用 PSR-6 的场景 ​

  • 需要批量延迟保存
  • 需要更细粒度的缓存控制
  • 需要检查缓存是否命中
  • 复杂的缓存逻辑
php
<?php

// PSR-6 适合复杂场景
$items = $cache->getItems($keys);
foreach ($items as $item) {
    if (!$item->isHit()) {
        $item->set(fetchData($item->getKey()));
        $cache->saveDeferred($item);
    }
}
$cache->commit();

使用 PSR-16 的场景 ​

  • 简单的键值缓存
  • 快速开发
  • 不需要复杂的缓存逻辑
php
<?php

// PSR-16 适合简单场景
$cache->set('key', 'value', 3600);
$value = $cache->get('key', 'default');

实际应用示例 ​

用户数据缓存 ​

php
<?php

declare(strict_types=1);

namespace App\Service;

use Psr\SimpleCache\CacheInterface;

class UserRepository
{
    public function __construct(
        private readonly CacheInterface $cache,
        private readonly \PDO $db
    ) {
    }

    public function find(int $id): ?array
    {
        $cacheKey = "user:{$id}";

        // 尝试从缓存获取
        $user = $this->cache->get($cacheKey);
        if ($user !== null) {
            return $user;
        }

        // 从数据库获取
        $stmt = $this->db->prepare('SELECT * FROM users WHERE id = ?');
        $stmt->execute([$id]);
        $user = $stmt->fetch(\PDO::FETCH_ASSOC);

        if ($user) {
            // 缓存用户数据,5分钟过期
            $this->cache->set($cacheKey, $user, 300);
        }

        return $user;
    }

    public function update(int $id, array $data): bool
    {
        // 更新数据库
        $stmt = $this->db->prepare('UPDATE users SET name = ?, email = ? WHERE id = ?');
        $result = $stmt->execute([$data['name'], $data['email'], $id]);

        if ($result) {
            // 删除缓存
            $this->cache->delete("user:{$id}");
        }

        return $result;
    }
}

配置缓存 ​

php
<?php

declare(strict_types=1);

namespace App\Service;

use Psr\Cache\CacheItemPoolInterface;

class ConfigService
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache
    ) {
    }

    public function get(string $key, mixed $default = null): mixed
    {
        $item = $this->cache->getItem("config:{$key}");

        if (!$item->isHit()) {
            $config = $this->loadConfig($key);
            $item->set($config);

            // 配置缓存 24 小时
            $item->expiresAfter(86400);
            $this->cache->save($item);
        }

        return $item->get() ?? $default;
    }

    public function set(string $key, mixed $value): void
    {
        $item = $this->cache->getItem("config:{$key}");
        $item->set($value);
        $item->expiresAfter(86400);
        $this->cache->save($item);
    }

    private function loadConfig(string $key): mixed
    {
        // 从配置源加载
        return null;
    }
}

API 响应缓存 ​

php
<?php

declare(strict_types=1);

namespace App\Middleware;

use Psr\SimpleCache\CacheInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CacheMiddleware
{
    public function __construct(
        private readonly CacheInterface $cache,
        private readonly int $ttl = 300
    ) {
    }

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $cacheKey = $this->getCacheKey($request);

        // 尝试从缓存获取响应
        $cachedResponse = $this->cache->get($cacheKey);
        if ($cachedResponse !== null) {
            return unserialize($cachedResponse);
        }

        // 执行请求处理器
        $response = $handler->handle($request);

        // 缓存响应
        $this->cache->set($cacheKey, serialize($response), $this->ttl);

        return $response;
    }

    private function getCacheKey(ServerRequestInterface $request): string
    {
        return 'response:'.md5($request->getUri()->getPath());
    }
}

错误处理 ​

异常处理 ​

Kuiper 缓存的键合法性校验由池层与各驱动统一执行(KeyValidator):键按 / 拆分后必须至少包含一个非空分段,''、'/'、'//' 这类没有任何非空分段的键会抛出 kuiper\cache\stash\InvalidArgumentException;键类型不是 string(如 int、float)时抛出的也是同一个异常(KeyValidator::normalize(),消息为 Cache key must be a non-empty string, "int" given.)。该异常同时实现 Psr\Cache\InvalidArgumentException 与 Psr\SimpleCache\InvalidArgumentException,并继承原生 \InvalidArgumentException,因此捕获 Psr\Cache\InvalidArgumentException、Psr\SimpleCache\InvalidArgumentException 或 \InvalidArgumentException 均可:

php
<?php

declare(strict_types=1);

use Psr\SimpleCache\CacheInterface;
use kuiper\cache\stash\InvalidArgumentException;

class SafeCacheService
{
    public function __construct(
        private readonly CacheInterface $cache
    ) {
    }

    public function getSafe(string $key, mixed $default = null): mixed
    {
        try {
            return $this->cache->get($key, $default);
        } catch (InvalidArgumentException $e) {
            // 缓存键非法:空键、不含任何非空分段,或键类型不是 string
            // (键类型错误抛出的也是这个异常,不是原生 \InvalidArgumentException)
            error_log("Invalid cache key: {$e->getMessage()}");
            return $default;
        } catch (\Throwable $e) {
            error_log("Cache error: {$e->getMessage()}");
            return $default;
        }
    }
}

只需一个 catch 分支

kuiper\cache\stash\InvalidArgumentException 继承原生 \InvalidArgumentException, 所以上面第一个 catch 分支已经覆盖了「键内容非法」与「键类型非法」两类错误; 再补一个 catch (\InvalidArgumentException $e) 分支是多余的——它永远不会被上面的 catch 抢先命中,且不会有其它原生 \InvalidArgumentException 从 PSR-16 的 get() / set() / delete() / has() 路径抛出。

setMultiple() 的值必须是 array/Traversable:SimpleCache(PSR-16 适配层)会显式 校验并抛出 kuiper\cache\stash\InvalidArgumentException(消息 Cache values must be array or Traversable, "string" given.); SwooleTableCache / ChainedCache 直接实现 PSR-16,方法签名上 $values 为 iterable,传入非可迭代值时由 PHP 抛 TypeError; ArrayCache 的 $values 参数未加类型约束,传入非可迭代值不会抛异常, 而是触发 PHP warning 后按空集合处理。 缓存操作本身不会抛出 Psr\Cache\CacheException / Psr\SimpleCache\CacheException。

性能优化 ​

批量操作优化 ​

php
<?php

declare(strict_types=1);

use Psr\SimpleCache\CacheInterface;

class OptimizedCacheService
{
    public function __construct(
        private readonly CacheInterface $cache
    ) {
    }

    public function getBatch(array $keys): array
    {
        // 使用批量获取而非循环单个获取
        return $this->cache->getMultiple($keys);
    }

    public function setBatch(array $items, int $ttl = 3600): bool
    {
        // 使用批量设置而非循环单个设置
        return $this->cache->setMultiple($items, $ttl);
    }
}

缓存预热 ​

php
<?php

declare(strict_types=1);

use Psr\Cache\CacheItemPoolInterface;

class CacheWarmupService
{
    public function __construct(
        private readonly CacheItemPoolInterface $cache
    ) {
    }

    public function warmup(array $keys): void
    {
        $deferred = [];

        foreach ($keys as $key) {
            $item = $this->cache->getItem($key);
            if (!$item->isHit()) {
                $data = $this->loadData($key);
                $item->set($data);
                $item->expiresAfter(3600);
                $deferred[] = $item;
            }
        }

        // 批量保存
        foreach ($deferred as $item) {
            $this->cache->saveDeferred($item);
        }
        $this->cache->commit();
    }

    private function loadData(string $key): mixed
    {
        // 加载数据
        return null;
    }
}

最佳实践 ​

  1. 使用有意义的缓存键:使用命名空间和描述性键名
  2. 设置合理的 TTL:根据数据更新频率设置过期时间
  3. 处理缓存未命中:提供默认值或从数据源获取
  4. 使用批量操作:减少缓存操作次数
  5. 监控缓存命中率:优化缓存策略
  6. 使用 PSR-16 进行简单操作:减少代码复杂度
  7. 使用 PSR-6 进行复杂操作:利用其高级特性

下一步 ​

基于 MIT 许可发布