silentbyte / litecache
一个轻量级、易于使用且简单的PHP缓存库。
Requires
- psr/log: ^1.0
- psr/simple-cache: ^1.0
Requires (Dev)
- mikey179/vfsstream: ^1.6
- monolog/monolog: ^1.22
- phpunit/phpunit: ^5.7
- sami/sami: ^4.0
Suggests
- monolog/monolog: Allows more advanced logging of the application flow
This package is auto-updated.
Last update: 2024-09-10 13:47:22 UTC
README
这是SilentByte LiteCache库的官方仓库。
LiteCache是一个轻量级、易于使用且符合PSR-16规范的PHP 7.0+缓存库,它试图利用PHP内置的缓存机制。在低成本托管提供商上,通常没有高级缓存系统,如Memcached。然而,代码/指令缓存通常被启用以加速执行。LiteCache通过为缓存对象生成*.php
文件来利用这一功能,然后由执行环境对其进行优化和缓存。
安装
安装最新版本的LiteCache最简单的方法是使用Composer
$ composer require silentbyte/litecache
更多信息可以在Packagist上找到。
如果您想不使用Composer直接检查和包含源代码,只需克隆此仓库
$ git clone https://github.com/SilentByte/litecache.git
通用用法
LiteCache实现了PSR-16,因此提供了一个标准化的API来存储和检索数据。完整的API文档在这里: LiteCache 2.0 API文档。
缓存入门
让我们从以下基本示例开始,该示例演示了如何从JSON文件加载和缓存应用程序的配置。
$cache = new \SilentByte\LiteCache\LiteCache(); $config = $cache->get('config'); if ($config === null) { $config = json_decode(file_get_contents('config.json'), true); $cache->set('config', $config); } var_dump($config);
方法$cache->get($key, $default = null)
和$cache->set($key, $value, $ttl = null)
用于从缓存中检索和保存配置,其唯一名称为config
,并遵守定义的TTL。在缓存未命中的情况下,数据将从实际的JSON文件中加载,然后立即进行缓存。
如果没有缓存作为中间层,则需要在每次请求时加载和解析JSON文件。LiteCache通过利用PHP的代码缓存机制避免了这个问题。
该库设计用于缓存任何类型的数据,包括整数、浮点数、字符串、布尔值、数组和对象。此外,LiteCache还提供了缓存文件和输出缓冲区内容的能力,以提供更快的访问。
高级缓存
存储和检索对象到和从缓存的主要方法是方法$cache->cache($name, $producer, $ttl)
。第一个参数$name
是要存储的对象的唯一名称。$producer
是一个生成器函数,如果对象已过期或尚未缓存,则会被调用。此callable
的返回值将被存储在缓存中。$ttl
或有效期定义了对象失效前的秒数。如果没有指定$ttl
,则使用缓存默认的有效期(在以下代码中为10分钟)。
以下示例使用cURL发出Github API请求,并将结果缓存10分钟。当代码第一次运行时,它将从Github服务器获取数据。后续对脚本的调用将访问缓存的值,而无需发出耗时请求。
// Create the cache object with a customized configuration. $cache = new \SilentByte\LiteCache\LiteCache([ // Specify the caching directory. 'directory' => '.litecache', // Make cached objects expire after 10 minutes. 'ttl' => '10 minutes' ]); // Issue a Github API request and cache it under the specified name ('git-request'). // Subsequent calls to $cache->cache() will be fetched from cache; // after expiration, a new request will be issued. $response = $cache->cache('git-request', function () { $ch = curl_init('https://api.github.com/users/SilentByte'); curl_setopt($ch, CURLOPT_USERAGENT, 'SilentByte/litecache'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); return json_decode(curl_exec($ch)); }); echo "Name: ", $response->login, "\n", "Website: ", $response->blog, "\n", "Update: ", $response->updated_at, "\n";
更多示例可以在该仓库的./examples/
目录中找到。
使用生成器
LiteCache的cache($key, $producer, $ttl)
方法使用生产者(实现为函数对象)来提供存储在缓存中的数据。LiteCache已经内置了一些有用的生产者,包括:FileProducer
、IniProducer
、JsonProducer
和OutputProducer
。
使用IniProducer
与以下*.ini
文件...
[server] host = myhost.test.com user = root password = root
...以及这段代码...
use SilentByte\LiteCache\IniProducer; use SilentByte\LiteCache\LiteCache; // Create the cache object with a customized configuration. $cache = new LiteCache([ // Cache objects permanently. 'ttl' => LiteCache::EXPIRE_NEVER ]); // Load the specified INI configuration file and cache it. $config = $cache->cache('ini-cache', new IniProducer('./sample_data/test_ini.ini')); echo "Host: ", $config['server']['host'], "\n", "User: ", $config['server']['user'], "\n", "Password: ", $config['server']['password'], "\n";
...将导致配置文件在脚本的所有后续调用中被缓存,从而避免在每次请求时进行不必要的解析。相同的原理也适用于其他类型的生产者。
相同的原理可以应用于缓存PHP的输出,例如,缓存一个网页以避免在每次请求时重新渲染它。实现这一点最简单的方法是使用内置的OutputProducer
use SilentByte\LiteCache\LiteCache; use SilentByte\LiteCache\OutputProducer; // Create the cache object with a customized configuration. $cache = new LiteCache([ // Specify the caching directory. 'directory' => '.litecache', // Cache objects for 30 seconds. 'ttl' => '30 seconds' ]); // Load the specified file and cache it. $output = $cache->cache('script-cache', new OutputProducer(function () { include('./sample_data/slow_script.php'); })); echo "---- (Script Output) -------------------\n"; echo $output; echo "---------------------------------------\n";
所有从包含的PHP脚本中输出的内容(例如,通过echo
生成)将被缓存30秒。如果你使用模板引擎,如Twig,可以使用OutputProducer
来缓存渲染的页面。如果数据直接以字符串的形式提供,简单的调用$cache->set($key, $value)
就足够了。
查看./examples/
文件夹获取更多详细信息。
选项
LiteCache的构造函数接受一个数组,用于指定用户定义的选项。
// LiteCache 2.1 Default Options. $options = [ 'directory' => '.litecache', 'subdivision' => false, 'pool' => 'default', 'ttl' => LiteCache::EXPIRE_NEVER, 'logger' => null ]; $cache = new LiteCache($options);
贡献
变更日志
查看CHANGELOG.md。
常见问题解答
LiteCache以什么许可证发布?
MIT许可证。查看LICENSE.txt获取详细信息。有关MIT许可证的更多信息,请参阅:https://open-source.org.cn/licenses/MIT
如何永久缓存静态文件,例如配置文件?
将$ttl
值设置为LiteCache::EXPIRE_NEVER
将导致对象保持缓存状态,直到手动删除缓存文件,无论是通过物理删除文件还是通过调用$cache->delete($key)
或$cache->clean()
。