yiisoft/cache
Composer 安装命令:
composer require yiisoft/cache
包简介
Yii Caching Library
README 文档
README
Yii Caching Library
This library is a wrapper around PSR-16 compatible caching libraries providing own features. It is used in Yii Framework but is usable separately.
Features
- Built on top of PSR-16, it can use any PSR-16 cache as a handler.
- Ability to set default TTL and key prefix per cache instance.
- Provides a built-in behavior to cache stampede prevention.
- Adds cache invalidation dependencies on top of PSR-16.
Requirements
- PHP 8.1 - 8.5.
mbstringPHP extension.
Installation
The package could be installed with Composer:
composer require yiisoft/cache
Configuration
There are two ways to get cache instance. If you need PSR-16 instance, you can simply create it:
$arrayCache = new \Yiisoft\Cache\ArrayCache();
In order to set a global key prefix:
$arrayCacheWithPrefix = new \Yiisoft\Cache\PrefixedCache(new \Yiisoft\Cache\ArrayCache(), 'myapp_');
If you need a simpler yet more powerful way to cache values based on recomputation callbacks use getOrSet()
and remove(), additional features such as invalidation dependencies and "Probably early expiration"
stampede prevention, you should wrap PSR-16 cache instance with \Yiisoft\Cache\Cache:
$cache = new \Yiisoft\Cache\Cache($arrayCache);
Set a default TTL:
$cache = new \Yiisoft\Cache\Cache($arrayCache, 60 * 60); // 1 hour
Ttl object
Ttl is a simple immutable value object that represents cache time-to-live (TTL) in seconds.
It eliminates magic numbers (like 60 * 60 or 3600), improves readability, and provides convenient factory methods.
Below are examples on how to use it.
If you're using PSR-16 cache adapter directly:
- TTL must be an integer number of seconds or
nullfor infinite lifetime. - Always use
->toSeconds()when usingTtlobject.
use Yiisoft\Cache\Ttl; use Yiisoft\Cache\ArrayCache; $cache = new ArrayCache(); $cache->set('key1', 'value1', Ttl::seconds(30)->toSeconds()); // 30 seconds $cache->set('key2', 'value2', Ttl::minutes(15)->toSeconds()); // 15 minutes $cache->set('key3', 'value3', Ttl::hours(2)->toSeconds()); // 2 hours $cache->set('key4', 'value4', Ttl::days(1)->toSeconds()); // 1 day // Complex durations $ttl = Ttl::create(sec: 30, min: 10, hour: 1); // 1 hour 10 minutes 30 seconds $cache->set('key', 'value', $ttl->toSeconds()); // Infinity / no expiration $cache->set('key6', 'value6', Ttl::forever()); // shorthand for null $cache->set('key7', 'value7', Ttl::from(null));
Creating and Normalizing TTL
The Ttl::from() method normalizes various TTL representations (Ttl, DateInterval, int, string, or null) into a Ttl object.
$ttl = Ttl::from(new DateInterval('PT45M')); // 45 minutes $ttl = Ttl::from(10); // 10 seconds $ttl = Ttl::from('12'); // 12 seconds $ttl = Ttl::from(null); // Infinity / no expiration $ttl = Ttl::from(Ttl::seconds(500)); $ttl = Ttl::create(sec: 30, min: 15); // From DateInterval $ttl = Ttl::fromInterval(new DateInterval('PT45M')); $cache->set('key', 'value', $ttl->toSeconds()); // Ttl::forever() is just a shorthand for `null` TTL (no expiration) $cache->set('key', 'value', Ttl::forever()->toSeconds()); // or $cache->set('key', 'value', Ttl::from(null)->toSeconds());
When using Ttl with Yii cache wrapper:
- You can pass a
Ttlobject in the constructor as the default value. - You can pass it to methods like
getOrSet()which expect integer number of seconds ornull.
use Yiisoft\Cache\Cache; use Yiisoft\Cache\ArrayCache; use Yiisoft\Cache\Ttl; $cache = new Cache(new ArrayCache(), Ttl::minutes(5)); // default TTL $cache->getOrSet('key', 'value'); // // Uses default TTL // Custom TTL $cache->getOrSet('key2', fn() => 'value2', Ttl::seconds(30)->toSeconds()); $cache->getOrSet('key3', fn() => 'value3', Ttl::forever()->toSeconds()); // No expiration Use `isForever()` to check if a TTL represents "forever" (i.e., no expiration). It returns true when the TTL value is null. ```php if (Ttl::from(null)->isForever()) { // No expiration }
Accessing TTL Value
Use toSeconds() to get the TTL in seconds (int) or null for "forever". The public $value property can be accessed directly (e.g., Ttl::seconds(30)->value), but toSeconds() is preferred for clarity.
$ttl = Ttl::seconds(60); $seconds = $ttl->toSeconds(); // Returns 60 $seconds = $ttl->value; // Also 60
Invalid TTL values
$ttl = Ttl::from('abc'); // Converts to 0 (expired) $ttl = Ttl::from(1.5); // TypeError: invalid TTL type
General usage
Typical PSR-16 cache usage is the following:
$cache = new \Yiisoft\Cache\ArrayCache(); $parameters = ['user_id' => 42]; $key = 'demo'; // Try retrieving $data from cache. $data = $cache->get($key); if ($data === null) { // $data is not found in cache, calculate it from scratch. $data = calculateData($parameters); // Store $data in cache for an hour so that it can be retrieved next time. $cache->set($key, $data, 3600); } // $data is available here.
In order to delete value you can use:
$cache->delete($key); // Or all cache $cache->clear();
To work with values in a more efficient manner, batch operations should be used:
getMultiple()setMultiple()deleteMultiple()
When using extended cache i.e. PSR-16 cache wrapped with \Yiisoft\Cache\Cache, you can use alternative syntax that
is less repetitive:
$cache = new \Yiisoft\Cache\Cache(new \Yiisoft\Cache\ArrayCache()); $key = ['top-products', $count = 10]; $data = $cache->getOrSet($key, function (\Psr\SimpleCache\CacheInterface $cache) use ($count) { return getTopProductsFromDatabase($count); }, 3600);
Normalization of the key occurs using the Yiisoft\Cache\CacheKeyNormalizer.
In order to delete value you can use:
$cache->remove($key);
You can use PSR-16 methods the following way, but remember that getting and setting the cache separately violates the "Probably early expiration" algorithm.
$value = $cache ->psr() ->get('myKey');
Invalidation dependencies
When using \Yiisoft\Cache\Cache, additionally to TTL for getOrSet() method you can specify a dependency
that may trigger cache invalidation. Below is an example using tag dependency:
/** * @var callable $callable * @var \Yiisoft\Cache\CacheInterface $cache */ use Yiisoft\Cache\Dependency\TagDependency; // Set multiple cache values marking both with a tag. $cache->getOrSet('item_42_price', $callable, null, new TagDependency('item_42')); $cache->getOrSet('item_42_total', $callable, 3600, new TagDependency('item_42')); // Trigger invalidation by tag. TagDependency::invalidate($cache, 'item_42');
Other dependencies:
Yiisoft\Cache\Dependency\CallbackDependency- invalidates the cache when callback result changes.Yiisoft\Cache\Dependency\FileDependency- invalidates the cache based on file modification time.Yiisoft\Cache\Dependency\ValueDependency- invalidates the cache when specified value changes.
You may combine multiple dependencies using Yiisoft\Cache\Dependency\AnyDependency
or Yiisoft\Cache\Dependency\AllDependencies.
In order to implement your own dependency extend from Yiisoft\Cache\Dependency\Dependency.
Cache stampede prevention
A cache stampede is a type of cascading failure that can occur when massively
parallel computing systems with caching mechanisms come under very high load. This behaviour is sometimes also called dog-piling.
The \Yiisoft\Cache\Cache uses a built-in "Probably early expiration" algorithm that prevents cache stampede.
This algorithm randomly fakes a cache miss for one user while others are still served the cached value.
You can control its behavior with the fifth optional parameter of getOrSet(), which is a float value called $beta.
By default, beta is 1.0, which is sufficient in most cases. The higher the value the earlier cache will be re-created.
/** * @var mixed $key * @var callable $callable * @var \DateInterval $ttl * @var \Yiisoft\Cache\CacheInterface $cache * @var \Yiisoft\Cache\Dependency\Dependency $dependency */ $beta = 2.0; $cache->getOrSet($key, $callable, $ttl, $dependency, $beta);
Cache handlers
Below the handler refers to the implementations of PSR-16.
This package contains two handlers:
Yiisoft\Cache\ArrayCache- provides caching for the current request only by storing the values in an array.Yiisoft\Cache\NullCache- does not cache anything reporting success for all methods calls.
Extra cache handlers are implemented as separate packages:
Data serialization
The package provides Yiisoft\Cache\Serializer\SerializerInterface for data serialization. It can be useful in database, file
or Redis cache implementations. Out of box, you can use Yiisoft\Cache\Serializer\PhpSerializer that works via PHP functions
serialize() and unserialize(). You can make own implementation, for example:
use Yiisoft\Cache\Serializer\SerializerInterface; final class IgbinarySerializer implements SerializerInterface { public function serialize(mixed $value) : string { return igbinary_serialize($value); } public function unserialize(string $data) : mixed { return igbinary_unserialize($data); } }
Documentation
If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.
License
The Yii Caching Library is free software. It is released under the terms of the BSD License.
Please see LICENSE for more information.
Maintained by Yii Software.
Support the project
Follow updates
yiisoft/cache 适用场景与选型建议
yiisoft/cache 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 938.2k 次下载、GitHub Stars 达 46, 最近一次更新时间为 2018 年 07 月 15 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「cache」 「yii」 「psr-16」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 yiisoft/cache 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 yiisoft/cache 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 yiisoft/cache 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
repository php library
Simple PSR-16 cache implementations for WordPress transient the OOP way
Yii2 LightBox image galary widget uses Lightbox v2.10.0 by Lokesh Dhakar
Laravel 5 - Repositories to the database layer
Priveate for SkeekS CMS
Always-offline PSR-16 cache implemention, for fallback and testing
统计信息
- 总下载量: 938.2k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 48
- 点击次数: 21
- 依赖项目数: 85
- 推荐数: 2
其他信息
- 授权协议: BSD-3-Clause
- 更新时间: 2018-07-15