shieldon/simple-cache

PSR-16 简单缓存驱动程序,适用于 PHP。

1.3.4 2023-07-14 06:36 UTC

This package is auto-updated.

Last update: 2024-09-14 09:19:50 UTC


README

缓存,一种常见的性能提升技术,是许多框架和库的基本特性。这种互操作性使得库可以利用现有的缓存实现,而不是创建自己的。PSR-6 解决了这个问题,但其正式和冗长的性质使得简单用例复杂化。PSR-16 采用了一种更简单的方法,旨在为常见情况创建一个简化的标准接口,以简单直接的方式确保与 PSR-6 的兼容性。

展示

Simple Cache 被用于 Cache Master,一个 WordPress 缓存插件,表现优异。如果您正在运行 WordPress 网站,不妨试试它;它不会让您失望。

内置驱动程序

需要标记的参数用星号 (*) 表示

注意

  • WinCache 由于仅在 Windows 上使用,且测试过程在 Linux 环境中进行,因此不包括在单元测试中。
  • unix_socket 默认为空,接受 Unix 域套接字文件的绝对路径。如果设置了它,则忽略 hostport

以下命令显示已安装的 PHP 模块列表。

php -m

在使用之前,请确保您的系统已安装所需的 PHP 模块。

目录

  • 安装
  • 用法
    • 缓存
      • 内置驱动程序
      • __construct
      • $driver
      • $config
  • API
    • set
    • get
    • has
    • delete
    • getMultiple
    • setMultiple
    • deleteMultiple
    • clear
    • clearExpiredItems (非 PSR-16)
  • 构建数据模式
    • MySQL
    • SQLite
  • 垃圾回收
  • 作者
  • 许可证

安装

composer require shieldon/simple-cache

用法

缓存

Cache 是一个适配器,不仅允许实现 Psr\SimpleCache\CacheInterface 的实例,而且还具有内置驱动程序。

__construct($driver = '', $config = [])

使用文件驱动程序创建缓存处理器。

示例

$driver = new \Shieldon\SimpleCache\Cache('file', [
    'storage' => __DIR__ . '/../tmp'
]);

$driver

(string|CacheInterface)

内置驱动程序的类名,或实现 Psr\SimpleCache\CacheInterface 的 PSR-16 驱动程序。

$config

(array)

将传递给内置驱动程序的一组参数。

示例

Redis

$config = [
    'host' => '127.0.0.1',
    'port' => 6379,
    'user' => null,
    'pass' => null,
];

文件

$config = [
    'storage' => '/tmp/simple-cache',
];

Mysql

$config = [
    'host'    => '127.0.0.1',
    'port'    => 3306,
    'user'    => null,
    'pass'    => null,
    'dbname'  => null,
    'table'   => 'cache_data',
    'charset' => 'utf8'
];

Sqlite

$config = [
    'storage' => '/tmp/simple-cache',
];

Mongo

$config = [
    'host'       => '127.0.0.1',
    'port'       => 27017,
    'user'       => null,
    'pass'       => null,
    'database'   => 'test',
    'collection' => 'cache_data',
];

MemcacheMemcached

$config = [
    'host' => '127.0.0.1',
    'port' => 11211,
];

API

这些 API 方法在 Psr\SimpleCache\CacheInterface 上定义。请查阅 PSR-16 文档 以获取详细说明。

  • set
  • get
  • has
  • delete
  • setMultiple
  • getMultiple
  • deleteMultiple
  • clear
  • clearExpiredItems (非 PSR-16)

set

public function set(string $key, mixed value, $ttl = null);

请注意,$ttl 接受 nullintDateIntervalnull 表示键将一直保留直到删除。

示例

$cache->set('foo', 'bar', 300);
$cache->set('foo2', 'bar2');

$array = [
    'hello' => 'world',
    'yes' => 'Taiwan',
];

$cache->set('foo3', $array);
$cache->set('foo4', $array, 300);

get

public function get(string $key, mixed $default = null): mixed

示例

echo $cache->get('foo', 'placeholder');
// bar

sleep(301);

echo $cache->get('foo', 'placeholder');
// placeholder

echo $cache->get('foo');
// null

echo $cache->get('foo2', 'placeholder');
// bar2

$example = $cache->get('foo3', 'placeholder');
var_dump($example);
// string(11) "placeholder"

$example = $cache->get('foo4', 'placeholder');
var_dump($example);
/* 
    array(2) {
    ["hello"]=>
    string(5) "world"
    ["yes"]=>
    string(6) "Taiwan"
    }
*/

has

public function has(string $key): bool

示例

if ($cache->has('foo3')) {
    echo 'foo3 exists.';
} else {
    echo 'foo3 does not exist.';
}
// foo3 exists.

delete

public function delete(string $key): bool

示例

if ($cache->delete('foo3')) {
    echo 'foo3 has been deleted successfully.';
} else {
    echo 'Failed to delete key foo3.';
}
// foo3 has been deleted successfully.

if ($cache->has('foo3')) {
    echo 'foo3 exists.';
} else {
    echo 'foo3 does not exist.';
}
// foo3 does not exist.

setMultiple

public function setMultiple(iterable $values, $ttl = null): bool

请注意,$ttl 接受 nullintDateIntervalnull 表示键将一直保留直到删除。

示例

$array = [
    'bar' => 'foo',
    'bar2' => 'foo2',
];

$cache->setMultiple($array, 300);

getMultiple

public function getMultiple(array $keys, mixed $default = null): iterable

示例

$example = $cache->getMultiple(['bar', 'bar2', 'bar3'], 'hello');
var_dump($example);
/* 
    array(3) {
    ["bar"]=>
    string(3) "foo"
    ["bar2"]=>
    string(4) "foo2"
    ["bar3"]=>
    string(5) "hello"
    }
*/

deleteMultiple

public function deleteMultiple(array $keys): bool

示例

if ($cache->deleteMultiple(['bar', 'bar2'])) {
    echo 'bar and bar2 have been deleted successfully.';
} else {
    echo 'Failed to delete keys bar or bar2.';
}
// bar and bar2 have been deleted successfully.

$example = $cache->getMultiple(['bar', 'bar2', 'bar3'], 'hello');
var_dump($example);
/* 
    array(3) {
    ["bar"]=>
    string(5) "hello"
    ["bar2"]=>
    string(5) "hello"
    ["bar3"]=>
    string(5) "hello"
    }
*/

clear

public function clear(): bool

示例

if ($cache->clear()) {
    echo 'All cached data has been deleted successfully.';
} else {
    echo 'Failed to delete the cached data.';
}
// All cached data has been deleted successfully.

clearExpiredItems 非 PSR-16

public function clearExpiredItems(): array

此方法返回已删除的缓存键列表。

注意RedisMemcacheMemcached 驱动程序将始终返回空数组。请参阅下面的 垃圾回收 部分。

示例

$cache->set('foo', 'bar', 300);
$cache->set('foo2', 'bar2', 5);
$cache->set('foo3', 'bar3', 5);

sleep(6);

$expiredItems = $cache->clearExpiredItems();
var_dump($expiredItems);

/* 
    array(2) {
    [0]=>
    string(4) "foo2"
    [1]=>
    string(4) "foo3"
    }
*/

构建数据模式

需要为 MySQL 和 SQLite 驱动程序的初始使用构建数据模式。

此 API 可用于此目的。

$cache->rebuild();

或手动构建。

MySQL

CREATE TABLE IF NOT EXISTS `cache_data` (
    `cache_key` varchar(40) NOT NULL,
    `cache_value` longtext,
    PRIMARY KEY (`cache_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

SQLite

CREATE TABLE IF NOT EXISTS cache_data (
    cache_key VARCHAR(40) PRIMARY KEY,
    cache_value LONGTEXT
);

垃圾回收

对于内置驱动程序,启用垃圾回收将自动从系统中清除过期的缓存。

使用以下参数

$config = [
    'gc_enable'      => true,
    'gc_divisor'     => 100, // default
    'gc_probability' => 1, // default
];

这意味着执行垃圾回收的 1% 概率。避免将其设置为 100%,因为这将不必要地逐个检索和检查所有键。

示例

$driver = new \Shieldon\SimpleCache\Cache('file', [
    'storage'   => __DIR__ . '/../tmp',
    'gc_enable' => true,
]);

您可以直接使用 gc_enable 来启用垃圾回收。

注意

对于Redis、Memcache和Memcached驱动程序,此方法不是必需的,因为过期的项会自动清除。

贡献

感谢您对我们项目的贡献兴趣!我们欢迎来自每个人的贡献。在开始之前,请花一点时间审查以下指南

指南

  • 从主分支Fork仓库并创建您的分支。
  • 确保您的代码遵循我们的编码风格和约定。
  • 保持您的代码简洁、有良好的文档和模块化。
  • 编写清晰的提交信息,描述您的更改目的。
  • 彻底测试您的更改,以确保它们不会引入任何新问题。
  • 确保您的代码构建成功,没有任何错误或警告。
  • 更新相关文档,包括必要时更新README文件。
  • 向原始仓库的主分支提交一个拉取请求(PR)。

代码测试

我们使用一个包含各种依赖关系的Docker镜像来测试我们的代码。该镜像基于/tests/Fixture/docker/Dockerfile,并预先配置了以下组件

  • Redis
  • MongoDB
  • MySQL
  • PHP
  • Memcached
  • APCu

按照以下步骤运行测试

  • 确保您已在您的机器上安装了Docker。如果没有,您可以从官方Docker网站下载并安装它。
  • 导航到项目目录,并运行以下命令来构建Docker镜像
    composer test:docker:build
    
  • 一旦Docker镜像构建完成,您可以通过执行以下命令来运行测试
    composer test:docker:run
    
  • 观察测试结果,并注意任何失败或错误。输出将在终端中显示。

作者

此库的起源

这个PHP库是为由台湾IT社区ITHelp举办的12th Ironman Game竞赛而创建的。我选择的主题是“PHP大师之路 - 开源代码的最佳实践”,用繁体中文撰写。如果您感兴趣,可以在这里阅读它:这里

许可证

MIT