tobento/service-cache

为 PHP 应用程序提供 PSR-6 和 PSR-16 缓存。

1.0.0 2023-06-29 09:30 UTC

This package is not auto-updated.

Last update: 2024-09-20 13:55:24 UTC


README

为 PHP 应用程序提供 PSR-6PSR-16 缓存。

目录

入门

使用以下命令添加缓存服务项目的最新版本。

composer require tobento/service-cache

需求

  • PHP 8.0 或更高版本

亮点

  • 框架无关,适用于任何项目
  • 解耦设计

文档

PSR 6 缓存

可用的缓存项池

文件存储缓存项池

文件存储缓存项池使用 文件存储服务 来存储项。

首先,您需要安装 service-file-storage

composer require tobento/service-file-storage

然后,创建您希望用于池的 文件存储

use Tobento\Service\Cache\FileStorageCacheItemPool;
use Tobento\Service\Cache\CanDeleteExpiredItems;
use Tobento\Service\Clock\SystemClock;
use Tobento\Service\FileStorage\StorageInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Clock\ClockInterface;

$pool = new FileStorageCacheItemPool(
    
    // Any storage where to store cache items:
    storage: $storage, // StorageInterface
    
    // A path used as the path prefix for the storage:
    path: 'cache', // string
    
    // The clock used for calculating expiration:
    clock: new SystemClock(), // ClockInterface
    
    // The default Time To Live in seconds, null forever:
    ttl: null, // null|int
);

var_dump($pool instanceof CacheItemPoolInterface);
// bool(true)

var_dump($pool instanceof CanDeleteExpiredItems);
// bool(true)

查看 可删除过期项 接口以了解更多信息。

存储缓存项池

存储缓存项池使用 存储服务 来存储项。

首先,您需要安装 service-storage

composer require tobento/service-storage

然后,创建您希望用于池的 存储

use Tobento\Service\Cache\StorageCacheItemPool;
use Tobento\Service\Cache\CanDeleteExpiredItems;
use Tobento\Service\Clock\SystemClock;
use Tobento\Service\Storage\StorageInterface;
use Tobento\Service\Storage\JsonFileStorage;
use Tobento\Service\Storage\Tables\Tables;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Clock\ClockInterface;

// Create the storage:
$tables = new Tables();
$tables->add('cache_items', ['id', 'data', 'expiration', 'namespace'], 'id');

$storage = new JsonFileStorage(
    dir: __DIR__.'/tmp/',
    tables: $tables
);

$pool = new StorageCacheItemPool(
    
    // Any storage where to store cache items:
    storage: $storage, // StorageInterface
    
    // A namespace used as prefix for cache item keys:
    namespace: 'default', // string
    
    // The clock used for calculating expiration:
    clock: new SystemClock(), // ClockInterface
    
    // The default Time To Live in seconds, null forever:
    ttl: null, // null|int
    
    // Specify the table name:
    table: 'cache_items', // string
);

var_dump($pool instanceof CacheItemPoolInterface);
// bool(true)

var_dump($pool instanceof CanDeleteExpiredItems);
// bool(true)

查看 可删除过期项 接口以了解更多信息。

(数据库)存储推荐表列类型

数组缓存项池

缓存项将在内存中存储,并以任何方式持久化到运行中的 PHP 进程之外。可能对测试目的有用。

use Tobento\Service\Cache\ArrayCacheItemPool;
use Tobento\Service\Clock\SystemClock;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Clock\ClockInterface;

$pool = new ArrayCacheItemPool(
    
    // The clock used for calculating expiration:
    clock: new SystemClock(), // ClockInterface
    
    // The default Time To Live in seconds, null forever:
    ttl: null, // null|int
);

var_dump($pool instanceof CacheItemPoolInterface);
// bool(true)

Psr16 缓存项池

使用定义的 Psr16 缓存来存储项的 Psr16 缓存项池。

use Tobento\Service\Cache\Psr16CacheItemPool;
use Tobento\Service\Cache\CanDeleteExpiredItems;
use Tobento\Service\Clock\SystemClock;
use Psr\SimpleCache\CacheInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Clock\ClockInterface;

$pool = new Psr16CacheItemPool(
    
    cache: $cache, // CacheInterface
    
    // A namespace used as prefix for cache item keys:
    namespace: 'default', // string
    
    // The clock used for calculating expiration:
    clock: new SystemClock(), // ClockInterface
    
    // The default Time To Live in seconds, null forever:
    ttl: null, // null|int
);

var_dump($pool instanceof CacheItemPoolInterface);
// bool(true)

var_dump($pool instanceof CanDeleteExpiredItems);
// bool(true)

缓存项池

创建池

use Tobento\Service\Cache\CacheItemPools;
use Tobento\Service\Cache\CacheItemPoolsInterface;

$pools = new CacheItemPools();

var_dump($pools instanceof CacheItemPoolsInterface);
// bool(true)

添加池

添加

use Psr\Cache\CacheItemPoolInterface;

$pools->add(
    name: 'primary',
    pool: $pool, // CacheItemPoolInterface
);

注册

您可以使用注册方法仅在请求时创建池。

use Psr\Cache\CacheItemPoolInterface;

$pools->register(
    name: 'name',
    pool: function(string $name): CacheItemPoolInterface {
        // create the pool:
        return $pool;
    },
);

获取池

如果池不存在或无法创建,则抛出 CacheException::class

use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\CacheException;

$pool = $pools->get(name: 'file');

var_dump($pool instanceof CacheItemPoolInterface);
// bool(true)

$pools->get(name: 'unknown');
// throws CacheException

您可以使用 has 方法检查池是否存在。

var_dump($pools->has('name'));
// bool(false)

您可以使用 getNames 方法获取所有池名称。

var_dump($pools->getNames());
// array(1) { [0]=> string(4) "file" }

默认池

您可以为应用程序设计添加默认池。

use Tobento\Service\Cache\CacheItemPools;
use Tobento\Service\Cache\CacheItemPoolsInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\CacheException;

$pools = new CacheItemPools();

// add "file" pool:
$pools->add(name: 'file', pool: $pool);

// add default:
$pools->addDefault(name: 'primary', pool: 'file');

// get default pool for the specified name.
$primaryPool = $pools->default('primary');

var_dump($primaryPool instanceof CacheItemPoolInterface);
// bool(true)

var_dump($pools->hasDefault('primary'));
// bool(true)

var_dump($pools->getDefaults());
// { ["primary"]=> string(4) "file" }

$pools->default('unknown');
// throws CacheException

接口

缓存项池工厂接口

您可以使用此接口创建池。

namespace Tobento\Service\Cache;

use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\CacheException;

interface CacheItemPoolFactoryInterface
{
    /**
     * Create a new CacheItemPool based on the configuration.
     *
     * @param string $name
     * @param array $config
     * @return CacheItemPoolInterface
     * @throws CacheException
     */
    public function createCacheItemPool(string $name, array $config = []): CacheItemPoolInterface;
}

缓存项池接口

namespace Tobento\Service\Cache;

use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\CacheException;

interface CacheItemPoolsInterface
{
    /**
     * Add a pool.
     *
     * @param string $name The pool name.
     * @param CacheItemPoolInterface $pool
     * @return static $this
     */
    public function add(string $name, CacheItemPoolInterface $pool): static;
    
    /**
     * Register a pool.
     *
     * @param string $name The pool name.
     * @param callable $pool
     * @return static $this
     */
    public function register(string $name, callable $pool): static;
    
    /**
     * Returns the pool by name.
     *
     * @param string $name The pool name
     * @return CacheItemPoolInterface
     * @throws CacheException
     */
    public function get(string $name): CacheItemPoolInterface;
    
    /**
     * Returns true if the pool exists, otherwise false.
     *
     * @param string $name The pool name.
     * @return bool
     */
    public function has(string $name): bool;

    /**
     * Adds a default name for the specified pool.
     *
     * @param string $name The default name.
     * @param string $pool The pool name.
     * @return static $this
     */
    public function addDefault(string $name, string $pool): static;

    /**
     * Returns the default pools.
     *
     * @return array<string, string> ['general' => 'files']
     */
    public function getDefaults(): array;
    
    /**
     * Returns the pool for the specified default name.
     *
     * @param string $name The type such as pdo.
     * @return CacheItemPoolInterface
     * @throws CacheException
     */
    public function default(string $name): CacheItemPoolInterface;
    
    /**
     * Returns true if the default pool exists, otherwise false.
     *
     * @param string $name The default name.
     * @return bool
     */
    public function hasDefault(string $name): bool;
    
    /**
     * Returns the names.
     *
     * @return array<int, string>
     */
    public function getNames(): array;
}

PSR 16 简单缓存

可用的缓存

Psr6 缓存

使用定义的 Psr6 池来存储项的 Psr6 缓存。

use Tobento\Service\Cache\Simple\Psr6Cache;
use Tobento\Service\Cache\ArrayCacheItemPool;
use Tobento\Service\Cache\CanDeleteExpiredItems;
use Tobento\Service\Clock\SystemClock;
use Psr\Cache\CacheItemPoolInterface;
use Psr\SimpleCache\CacheInterface;
use Psr\Clock\ClockInterface;

$pool = new ArrayCacheItemPool(
    clock: new SystemClock(),
);

$cache = new Psr6Cache(
    
    pool: $pool, // CacheItemPoolInterface
    
    // A namespace used as prefix for cache item keys:
    namespace: 'default', // string
    
    // The default Time To Live in seconds, null forever:
    ttl: null, // null|int
);

var_dump($cache instanceof CacheInterface);
// bool(true)

var_dump($cache instanceof CanDeleteExpiredItems);
// bool(true)

查看 可删除过期项 接口以了解更多信息。

缓存

创建缓存

use Tobento\Service\Cache\Simple\Caches;
use Tobento\Service\Cache\Simple\CachesInterface;

$caches = new Caches();

var_dump($caches instanceof CachesInterface);
// bool(true)

添加缓存

添加

use Psr\SimpleCache\CacheInterface;

$caches->add(
    name: 'primary',
    cache: $cache, // CacheInterface
);

注册

您可以使用注册方法仅在请求时创建缓存。

use Psr\SimpleCache\CacheInterface;

$caches->register(
    name: 'name',
    cache: function(string $name): CacheInterface {
        // create the cache:
        return $cache;
    },
);

获取缓存

如果缓存不存在或无法创建,则抛出 CacheException::class

use Psr\SimpleCache\CacheInterface;
use Psr\SimpleCache\CacheException;

$cache = $caches->get(name: 'file');

var_dump($cache instanceof CacheInterface);
// bool(true)

$caches->get(name: 'unknown');
// throws CacheException

您可以使用 has 方法检查缓存是否存在。

var_dump($caches->has('name'));
// bool(false)

您可以使用 getNames 方法获取所有缓存名称。

var_dump($caches->getNames());
// array(1) { [0]=> string(4) "file" }

默认缓存

您可以为应用程序设计添加默认缓存。

$caches = new Caches();

// add "file" cache:
$caches->add(name: 'file', cache: $cache);

// add default:
$caches->addDefault(name: 'primary', cache: 'file');

// get default cache for the specified name.
$primaryPool = $caches->default('primary');

var_dump($primaryPool instanceof CacheInterface);
// bool(true)

var_dump($caches->hasDefault('primary'));
// bool(true)

var_dump($caches->getDefaults());
// { ["primary"]=> string(4) "file" }

$caches->default('unknown');
// throws CacheException

简单接口

缓存工厂接口

您可以使用此接口创建缓存。

namespace Tobento\Service\Cache\Simple;

use Psr\SimpleCache\CacheInterface;
use Psr\SimpleCache\CacheException;

interface CacheFactoryInterface
{
    /**
     * Create a new Cache based on the configuration.
     *
     * @param string $name
     * @param array $config
     * @return CacheInterface
     * @throws CacheException
     */
    public function createCache(string $name, array $config = []): CacheInterface;
}

缓存接口

namespace Tobento\Service\Cache\Simple;

use Psr\SimpleCache\CacheInterface;
use Psr\SimpleCache\CacheException;

interface CachesInterface
{
    /**
     * Add a cache.
     *
     * @param string $name The cache name.
     * @param CacheInterface $cache
     * @return static $this
     */
    public function add(string $name, CacheInterface $cache): static;
    
    /**
     * Register a cache.
     *
     * @param string $name The cache name.
     * @param callable $cache
     * @return static $this
     */
    public function register(string $name, callable $cache): static;
    
    /**
     * Returns the cache by name.
     *
     * @param string $name The cache name
     * @return CacheInterface
     * @throws CacheException
     */
    public function get(string $name): CacheInterface;
    
    /**
     * Returns true if the cache exists, otherwise false.
     *
     * @param string $name The cache name.
     * @return bool
     */
    public function has(string $name): bool;

    /**
     * Adds a default name for the specified cache.
     *
     * @param string $name The default name.
     * @param string $cache The cache name.
     * @return static $this
     */
    public function addDefault(string $name, string $cache): static;

    /**
     * Returns the default caches.
     *
     * @return array<string, string> ['general' => 'files']
     */
    public function getDefaults(): array;
    
    /**
     * Returns the cache for the specified default name.
     *
     * @param string $name The type such as pdo.
     * @return CacheInterface
     * @throws CacheException
     */
    public function default(string $name): CacheInterface;
    
    /**
     * Returns true if the default cache exists, otherwise false.
     *
     * @param string $name The default name.
     * @return bool
     */
    public function hasDefault(string $name): bool;
    
    /**
     * Returns the names.
     *
     * @return array<int, string>
     */
    public function getNames(): array;
}

共享接口

可删除过期项

namespace Tobento\Service\Cache;

interface CanDeleteExpiredItems
{
    /**
     * Removes all expired items from the pool or cache.
     *
     * @return bool
     *   True if the items were successfully removed. False if there was an error.
     */
    public function deleteExpiredItems(): bool;
}

鸣谢