PHPackages                             yiisoft/cache - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. yiisoft/cache

ActiveLibrary[Framework](/categories/framework)

yiisoft/cache
=============

Yii Caching Library

3.2.0(6mo ago)48956.1k↑30.6%2020BSD-3-ClausePHPPHP 8.1 - 8.5CI passing

Since Feb 2Pushed 5mo ago19 watchersCompare

[ Source](https://github.com/yiisoft/cache)[ Packagist](https://packagist.org/packages/yiisoft/cache)[ Docs](https://www.yiiframework.com/)[ GitHub Sponsors](https://github.com/sponsors/yiisoft)[ OpenCollective](https://opencollective.com/yiisoft)[ RSS](/packages/yiisoft-cache/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (4)Dependencies (8)Versions (9)Used By (20)

 [ ![Yii](https://camo.githubusercontent.com/8317c17418b39410a660f5149071d26c5023c0d5fb2b7ebb771324812f666d73/68747470733a2f2f796969736f66742e6769746875622e696f2f646f63732f696d616765732f7969695f6c6f676f2e737667) ](https://github.com/yiisoft)

Yii Caching Library
===================

[](#yii-caching-library)

[![Latest Stable Version](https://camo.githubusercontent.com/afb6c10a8e46d23709cd0c67a8c4d755df9705c065dd4b2d3a28fa2b5b670726/68747470733a2f2f706f7365722e707567782e6f72672f796969736f66742f63616368652f76)](https://packagist.org/packages/yiisoft/cache)[![Total Downloads](https://camo.githubusercontent.com/1b2440ce4f21850827507faf363ba5d69edc572c3a9c675d8d3a86b7e811f3c2/68747470733a2f2f706f7365722e707567782e6f72672f796969736f66742f63616368652f646f776e6c6f616473)](https://packagist.org/packages/yiisoft/cache)[![Build status](https://github.com/yiisoft/cache/actions/workflows/build.yml/badge.svg)](https://github.com/yiisoft/cache/actions/workflows/build.yml)[![Code Coverage](https://camo.githubusercontent.com/186dfe7d8fa58510d9acbd48c38949beb4e87a7dbd047c868f98203897224543/68747470733a2f2f636f6465636f762e696f2f67682f796969736f66742f63616368652f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/yiisoft/cache)[![Mutation testing badge](https://camo.githubusercontent.com/b9ee1f328ab985838cc66babd2b61bff5f08c848f6c4875a267746337a3539f1/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f7374796c653d666c61742675726c3d687474707325334125324625324662616467652d6170692e737472796b65722d6d757461746f722e696f2532466769746875622e636f6d253246796969736f667425324663616368652532466d6173746572)](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/cache/master)[![static analysis](https://github.com/yiisoft/cache/workflows/static%20analysis/badge.svg)](https://github.com/yiisoft/cache/actions?query=workflow%3A%22static+analysis%22)[![psalm-level](https://camo.githubusercontent.com/224a3266ccda11a328d54703cd22e1a29d13adcc4a91eda322230d6c1a50208d/68747470733a2f2f73686570686572642e6465762f6769746875622f796969736f66742f63616368652f6c6576656c2e737667)](https://shepherd.dev/github/yiisoft/cache)[![type-coverage](https://camo.githubusercontent.com/1e513e4b152fec26c4e40f11cb5c94dd0cf40856132c6457341a103ae748e15e/68747470733a2f2f73686570686572642e6465762f6769746875622f796969736f66742f63616368652f636f7665726167652e737667)](https://shepherd.dev/github/yiisoft/cache)

This library is a wrapper around [PSR-16](https://www.php-fig.org/psr/psr-16/) compatible caching libraries providing own features. It is used in [Yii Framework](https://www.yiiframework.com/) but is usable separately.

Features
--------

[](#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
------------

[](#requirements)

- PHP 8.1 - 8.5.
- `mbstring` PHP extension.

Installation
------------

[](#installation)

The package could be installed with [Composer](https://getcomposer.org):

```
composer require yiisoft/cache
```

Configuration
-------------

[](#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-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 `null` for infinite lifetime.
- Always use `->toSeconds()` when using `Ttl` object.

```
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

[](#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:

[](#when-using-ttl-with-yii-cache-wrapper)

- You can pass a `Ttl` object in the constructor as the default value.
- You can pass it to methods like `getOrSet()` which expect integer number of seconds or `null`.

```
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

[](#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

[](#invalid-ttl-values)

```
$ttl = Ttl::from('abc'); // Converts to 0 (expired)
$ttl = Ttl::from(1.5);   // TypeError: invalid TTL type
```

General usage
-------------

[](#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

[](#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

[](#cache-stampede-prevention)

[A cache stampede](https://en.wikipedia.org/wiki/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

[](#cache-handlers)

> Below the handler refers to the implementations of [PSR-16](https://www.php-fig.org/psr/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:

- [APCu](https://github.com/yiisoft/cache-apcu)
- [Database](https://github.com/yiisoft/cache-db)
- [File](https://github.com/yiisoft/cache-file)
- [Memcached](https://github.com/yiisoft/cache-memcached)
- [Redis](https://github.com/yiisoft/cache-redis)
- [Wincache](https://github.com/yiisoft/cache-wincache)

### Data serialization

[](#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
-------------

[](#documentation)

- [Internals](docs/internals.md)

If you need help or have a question, the [Yii Forum](https://forum.yiiframework.com/c/yii-3-0/63) is a good place for that. You may also check out other [Yii Community Resources](https://www.yiiframework.com/community).

License
-------

[](#license)

The Yii Caching Library is free software. It is released under the terms of the BSD License. Please see [`LICENSE`](./LICENSE.md) for more information.

Maintained by [Yii Software](https://www.yiiframework.com/).

Support the project
-------------------

[](#support-the-project)

[![Open Collective](https://camo.githubusercontent.com/a2b15f8e2268d4e3842e00d41ff7a57cce2ad8bd8d8769c5dc4fa05a546a4f62/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4f70656e253230436f6c6c6563746976652d73706f6e736f722d3765616466313f6c6f676f3d6f70656e253230636f6c6c656374697665266c6f676f436f6c6f723d376561646631266c6162656c436f6c6f723d353535353535)](https://opencollective.com/yiisoft)

Follow updates
--------------

[](#follow-updates)

[![Official website](https://camo.githubusercontent.com/d6b0929173e28cc627430d2519ca1853466a70f37395877eaf4820cb3e1e1909/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f506f77657265645f62792d5969695f4672616d65776f726b2d677265656e2e7376673f7374796c653d666c6174)](https://www.yiiframework.com/)[![Twitter](https://camo.githubusercontent.com/d077c362ac639792171af8bc002ee827816733dfc0925f70b557e6d151022226/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f747769747465722d666f6c6c6f772d3144413146323f6c6f676f3d74776974746572266c6f676f436f6c6f723d314441314632266c6162656c436f6c6f723d3535353535353f7374796c653d666c6174)](https://twitter.com/yiiframework)[![Telegram](https://camo.githubusercontent.com/4e38dd12535575c39c65bea7119b95e663abb2d1f4e3d669a27bbda07ef603f0/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74656c656772616d2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d74656c656772616d)](https://t.me/yii3en)[![Facebook](https://camo.githubusercontent.com/48204e301b34b29b0815854544f04c337fc0692096cab35e9a1f8c53a42c2307/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f66616365626f6f6b2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d66616365626f6f6b266c6f676f436f6c6f723d666666666666)](https://www.facebook.com/groups/yiitalk)[![Slack](https://camo.githubusercontent.com/1a3645ba1c97e6684d0349bc478201e1621ba0d3efad516d81035364d442bad7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f736c61636b2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d736c61636b)](https://yiiframework.com/go/slack)

###  Health Score

63

—

FairBetter than 99% of packages

Maintenance70

Regular maintenance activity

Popularity52

Moderate usage in the ecosystem

Community44

Growing community involvement

Maturity76

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~354 days

Recently: every ~430 days

Total

6

Last Release

204d ago

Major Versions

1.0.1 → 2.0.02022-06-29

2.0.0 → 3.0.02023-02-15

PHP version history (4 changes)1.0.0PHP ^7.4|^8.0

2.0.0PHP ^8.0

3.1.0PHP 8.1 - 8.4

3.2.0PHP 8.1 - 8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/261a6249c6f605f3956a2fae40fbb813f6b2e1e6f2bf806180c851a965426e54?d=identicon)[cebe](/maintainers/cebe)

![](https://www.gravatar.com/avatar/fc29e4e7068a00fe9b9db37b8aadda1db6020adcacef810461e47b99c2b150e6?d=identicon)[samdark](/maintainers/samdark)

![](https://www.gravatar.com/avatar/ccb75e3312d6bd454ea445ea308139fd185a4ca906ca5df21cc66e6a35de25a3?d=identicon)[SilverFire](/maintainers/SilverFire)

![](https://www.gravatar.com/avatar/99106256c24a8cb23871b99fa90e48f37f1aa71608c185759b7d2a88683a5918?d=identicon)[hiqsol](/maintainers/hiqsol)

---

Top Contributors

[![samdark](https://avatars.githubusercontent.com/u/47294?v=4)](https://github.com/samdark "samdark (138 commits)")[![alexkart](https://avatars.githubusercontent.com/u/8249105?v=4)](https://github.com/alexkart "alexkart (37 commits)")[![hiqsol](https://avatars.githubusercontent.com/u/11820365?v=4)](https://github.com/hiqsol "hiqsol (24 commits)")[![devanych](https://avatars.githubusercontent.com/u/20116244?v=4)](https://github.com/devanych "devanych (22 commits)")[![vjik](https://avatars.githubusercontent.com/u/525501?v=4)](https://github.com/vjik "vjik (21 commits)")[![machour](https://avatars.githubusercontent.com/u/304450?v=4)](https://github.com/machour "machour (14 commits)")[![xepozz](https://avatars.githubusercontent.com/u/6815714?v=4)](https://github.com/xepozz "xepozz (13 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (8 commits)")[![terabytesoftw](https://avatars.githubusercontent.com/u/42547589?v=4)](https://github.com/terabytesoftw "terabytesoftw (6 commits)")[![alex-krash](https://avatars.githubusercontent.com/u/5325438?v=4)](https://github.com/alex-krash "alex-krash (5 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (4 commits)")[![luizcmarin](https://avatars.githubusercontent.com/u/67489841?v=4)](https://github.com/luizcmarin "luizcmarin (4 commits)")[![Fantom409](https://avatars.githubusercontent.com/u/14968877?v=4)](https://github.com/Fantom409 "Fantom409 (3 commits)")[![mspirkov](https://avatars.githubusercontent.com/u/63721828?v=4)](https://github.com/mspirkov "mspirkov (2 commits)")[![sankaest](https://avatars.githubusercontent.com/u/21160342?v=4)](https://github.com/sankaest "sankaest (2 commits)")[![SilverFire](https://avatars.githubusercontent.com/u/4499203?v=4)](https://github.com/SilverFire "SilverFire (1 commits)")[![skugarev](https://avatars.githubusercontent.com/u/22639131?v=4)](https://github.com/skugarev "skugarev (1 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (1 commits)")[![viktorprogger](https://avatars.githubusercontent.com/u/7670669?v=4)](https://github.com/viktorprogger "viktorprogger (1 commits)")[![cebe](https://avatars.githubusercontent.com/u/189796?v=4)](https://github.com/cebe "cebe (1 commits)")

---

Tags

cachehacktoberfestpsr-16yii3cachepsr-16yii

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm, Rector

Type Coverage Yes

### Embed Badge

![Health badge](/badges/yiisoft-cache/health.svg)

```
[![Health](https://phpackages.com/badges/yiisoft-cache/health.svg)](https://phpackages.com/packages/yiisoft-cache)
```

###  Alternatives

[laravel/framework

The Laravel Framework.

34.8k543.8M20.1k](/packages/laravel-framework)[cakephp/cakephp

The CakePHP framework

8.9k19.5M1.8k](/packages/cakephp-cakephp)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

85036.3k](/packages/flow-php-flow)[cakephp/cache

Easy to use Caching library with support for multiple caching backends

518.7M24](/packages/cakephp-cache)[nutgram/nutgram

The Telegram bot library that doesn't drive you nuts

737290.3k8](/packages/nutgram-nutgram)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M574](/packages/shopware-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
