PHPackages                             react/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. [Caching](/categories/caching)
4. /
5. react/cache

ActiveLibrary[Caching](/categories/caching)

react/cache
===========

Async, Promise-based cache interface for ReactPHP

v1.2.0(3y ago)444112.4M—2.3%18[1 issues](https://github.com/reactphp/cache/issues)20MITPHPPHP &gt;=5.3.0CI passing

Since Dec 24Pushed 1w ago11 watchersCompare

[ Source](https://github.com/reactphp/cache)[ Packagist](https://packagist.org/packages/react/cache)[ Fund](https://opencollective.com/reactphp)[ RSS](/packages/react-cache/feed)WikiDiscussions 3.x Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (14)Used By (20)

Cache
=====

[](#cache)

[![CI status](https://github.com/reactphp/cache/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/cache/actions)[![installs on Packagist](https://camo.githubusercontent.com/c7f8bd9a3e6ae4ea8063f5c03d1dd93dd4523c90c31f6ed8e61e78efc0a7e2c9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f72656163742f63616368653f636f6c6f723d626c7565266c6162656c3d696e7374616c6c732532306f6e2532305061636b6167697374)](https://packagist.org/packages/react/cache)

Async, [Promise](https://github.com/reactphp/promise)-based cache interface for [ReactPHP](https://reactphp.org/).

> **Development version:** This branch contains the code for the upcoming v3 release. For the code of the current stable v1 release, check out the [`1.x` branch](https://github.com/reactphp/cache/tree/1.x).
>
> The upcoming v3 release will be the way forward for this package. However, we will still actively support v1 for those not yet on the latest version. See also [installation instructions](#install) for more details.

The cache component provides a [Promise](https://github.com/reactphp/promise)-based [`CacheInterface`](#cacheinterface) and an in-memory [`ArrayCache`](#arraycache)implementation of that. This allows consumers to type hint against the interface and third parties to provide alternate implementations. This project is heavily inspired by [PSR-16: Common Interface for Caching Libraries](https://www.php-fig.org/psr/psr-16/), but uses an interface more suited for async, non-blocking applications.

**Table of Contents**

- [Usage](#usage)
    - [CacheInterface](#cacheinterface)
        - [get()](#get)
        - [set()](#set)
        - [delete()](#delete)
        - [getMultiple()](#getmultiple)
        - [setMultiple()](#setmultiple)
        - [deleteMultiple()](#deletemultiple)
        - [clear()](#clear)
        - [has()](#has)
    - [ArrayCache](#arraycache)
- [Common usage](#common-usage)
    - [Fallback get](#fallback-get)
    - [Fallback-get-and-set](#fallback-get-and-set)
- [Install](#install)
- [Tests](#tests)
- [License](#license)

Usage
-----

[](#usage)

### CacheInterface

[](#cacheinterface)

The `CacheInterface` describes the main interface of this component. This allows consumers to type hint against the interface and third parties to provide alternate implementations.

#### get()

[](#get)

The `get(string $key, mixed $default = null): PromiseInterface` method can be used to retrieve an item from the cache.

This method will resolve with the cached value on success or with the given `$default` value when no item can be found or when an error occurs. Similarly, an expired cache item (once the time-to-live is expired) is considered a cache miss.

```
$cache
    ->get('foo')
    ->then('var_dump');
```

This example fetches the value of the key `foo` and passes it to the `var_dump` function. You can use any of the composition provided by [promises](https://github.com/reactphp/promise).

#### set()

[](#set)

The `set(string $key, mixed $value, ?float $ttl = null): PromiseInterface` method can be used to store an item in the cache.

This method will resolve with `true` on success or `false` when an error occurs. If the cache implementation has to go over the network to store it, it may take a while.

The optional `$ttl` parameter sets the maximum time-to-live in seconds for this cache item. If this parameter is omitted (or `null`), the item will stay in the cache for as long as the underlying implementation supports. Trying to access an expired cache item results in a cache miss, see also [`get()`](#get).

```
$cache->set('foo', 'bar', 60);
```

This example eventually sets the value of the key `foo` to `bar`. If it already exists, it is overridden.

This interface does not enforce any particular TTL resolution, so special care may have to be taken if you rely on very high precision with millisecond accuracy or below. Cache implementations SHOULD work on a best effort basis and SHOULD provide at least second accuracy unless otherwise noted. Many existing cache implementations are known to provide microsecond or millisecond accuracy, but it's generally not recommended to rely on this high precision.

This interface suggests that cache implementations SHOULD use a monotonic time source if available. Given that a monotonic time source is only available as of PHP 7.3 by default, cache implementations MAY fall back to using wall-clock time. While this does not affect many common use cases, this is an important distinction for programs that rely on a high time precision or on systems that are subject to discontinuous time adjustments (time jumps). This means that if you store a cache item with a TTL of 30s and then adjust your system time forward by 20s, the cache item SHOULD still expire in 30s.

#### delete()

[](#delete)

The `delete(string $key): PromiseInterface` method can be used to delete an item from the cache.

This method will resolve with `true` on success or `false` when an error occurs. When no item for `$key` is found in the cache, it also resolves to `true`. If the cache implementation has to go over the network to delete it, it may take a while.

```
$cache->delete('foo');
```

This example eventually deletes the key `foo` from the cache. As with `set()`, this may not happen instantly and a promise is returned to provide guarantees whether or not the item has been removed from cache.

#### getMultiple()

[](#getmultiple)

The `getMultiple(iterable $keys, mixed $default = null): PromiseInterface` method can be used to retrieve multiple cache items by their unique keys.

This method will resolve with an array of cached values on success or with the given `$default` value when an item can not be found or when an error occurs. Similarly, an expired cache item (once the time-to-live is expired) is considered a cache miss.

```
$cache->getMultiple(['name', 'age'])->then(function (iterable $values): void {
    $array = is_array($values) ? $values : iterator_to_array($values);
    $name = $array['name'] ?? 'User';
    $age = $array['age'] ?? 'n/a';

    echo $name . ' is ' . $age . PHP_EOL;
});
```

This example fetches the cache items for the `name` and `age` keys and prints some example output. You can use any of the composition provided by [promises](https://github.com/reactphp/promise).

#### setMultiple()

[](#setmultiple)

The `setMultiple(iterable $values, ?float $ttl = null): PromiseInterface` method can be used to persist a set of key =&gt; value pairs in the cache, with an optional TTL.

This method will resolve with `true` on success or `false` when an error occurs. If the cache implementation has to go over the network to store it, it may take a while.

The optional `$ttl` parameter sets the maximum time-to-live in seconds for these cache items. If this parameter is omitted (or `null`), these items will stay in the cache for as long as the underlying implementation supports. Trying to access an expired cache items results in a cache miss, see also [`getMultiple()`](#getmultiple).

```
$cache->setMultiple(['foo' => 1, 'bar' => 2], 60);
```

This example eventually sets the list of values - the key `foo` to `1` value and the key `bar` to `2`. If some of the keys already exist, they are overridden.

#### deleteMultiple()

[](#deletemultiple)

The `setMultiple(iterable $keys): PromiseInterface` method can be used to delete multiple cache items in a single operation.

This method will resolve with `true` on success or `false` when an error occurs. When no items for `$keys` are found in the cache, it also resolves to `true`. If the cache implementation has to go over the network to delete it, it may take a while.

```
$cache->deleteMultiple(['foo', 'bar, 'baz']);
```

This example eventually deletes keys `foo`, `bar` and `baz` from the cache. As with `setMultiple()`, this may not happen instantly and a promise is returned to provide guarantees whether or not the item has been removed from cache.

#### clear()

[](#clear)

The `clear(): PromiseInterface` method can be used to wipe clean the entire cache.

This method will resolve with `true` on success or `false` when an error occurs. If the cache implementation has to go over the network to delete it, it may take a while.

```
$cache->clear();
```

This example eventually deletes all keys from the cache. As with `deleteMultiple()`, this may not happen instantly and a promise is returned to provide guarantees whether or not all the items have been removed from cache.

#### has()

[](#has)

The `has(string $key): PromiseInterface` method can be used to determine whether an item is present in the cache.

This method will resolve with `true` on success or `false` when no item can be found or when an error occurs. Similarly, an expired cache item (once the time-to-live is expired) is considered a cache miss.

```
$cache
    ->has('foo')
    ->then('var_dump');
```

This example checks if the value of the key `foo` is set in the cache and passes the result to the `var_dump` function. You can use any of the composition provided by [promises](https://github.com/reactphp/promise).

NOTE: It is recommended that has() is only to be used for cache warming type purposes and not to be used within your live applications operations for get/set, as this method is subject to a race condition where your has() will return true and immediately after, another script can remove it making the state of your app out of date.

### ArrayCache

[](#arraycache)

The `ArrayCache` provides an in-memory implementation of the [`CacheInterface`](#cacheinterface).

```
$cache = new ArrayCache();

$cache->set('foo', 'bar');
```

Its constructor accepts an optional `?int $limit` parameter to limit the maximum number of entries to store in the LRU cache. If you add more entries to this instance, it will automatically take care of removing the one that was least recently used (LRU).

For example, this snippet will overwrite the first value and only store the last two entries:

```
$cache = new ArrayCache(2);

$cache->set('foo', '1');
$cache->set('bar', '2');
$cache->set('baz', '3');
```

This cache implementation is known to rely on wall-clock time to schedule future cache expiration times when using any version before PHP 7.3, because a monotonic time source is only available as of PHP 7.3 (`hrtime()`). While this does not affect many common use cases, this is an important distinction for programs that rely on a high time precision or on systems that are subject to discontinuous time adjustments (time jumps). This means that if you store a cache item with a TTL of 30s on PHP &lt; 7.3 and then adjust your system time forward by 20s, the cache item may expire in 10s. See also [`set()`](#set) for more details.

Common usage
------------

[](#common-usage)

### Fallback get

[](#fallback-get)

A common use case of caches is to attempt fetching a cached value and as a fallback retrieve it from the original data source if not found. Here is an example of that:

```
$cache
    ->get('foo')
    ->then(function ($result) {
        if ($result === null) {
            return getFooFromDb();
        }

        return $result;
    })
    ->then('var_dump');
```

First an attempt is made to retrieve the value of `foo`. A callback function is registered that will call `getFooFromDb` when the resulting value is null. `getFooFromDb` is a function (can be any PHP callable) that will be called if the key does not exist in the cache.

`getFooFromDb` can handle the missing key by returning a promise for the actual value from the database (or any other data source). As a result, this chain will correctly fall back, and provide the value in both cases.

### Fallback get and set

[](#fallback-get-and-set)

To expand on the fallback get example, often you want to set the value on the cache after fetching it from the data source.

```
$cache
    ->get('foo')
    ->then(function ($result) {
        if ($result === null) {
            return $this->getAndCacheFooFromDb();
        }

        return $result;
    })
    ->then('var_dump');

public function getAndCacheFooFromDb()
{
    return $this->db
        ->get('foo')
        ->then([$this, 'cacheFooFromDb']);
}

public function cacheFooFromDb($foo)
{
    $this->cache->set('foo', $foo);

    return $foo;
}
```

By using chaining you can easily conditionally cache the value if it is fetched from the database.

Install
-------

[](#install)

The recommended way to install this library is [through Composer](https://getcomposer.org). [New to Composer?](https://getcomposer.org/doc/00-intro.md)

Once released, this project will follow [SemVer](https://semver.org/). At the moment, this will install the latest development version:

```
composer require react/cache:^3@dev
```

See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades.

This project aims to run on any platform and thus does not require any PHP extensions and supports running on PHP 7.1 through current PHP 8+. It's *highly recommended to use the latest supported PHP version* for this project.

Tests
-----

[](#tests)

To run the test suite, you first need to clone this repo and then install all dependencies [through Composer](https://getcomposer.org):

```
composer install
```

To run the test suite, go to the project root and run:

```
vendor/bin/phpunit
```

On top of this, we use PHPStan on max level to ensure type safety across the project:

```
vendor/bin/phpstan
```

License
-------

[](#license)

MIT, see [LICENSE file](LICENSE).

###  Health Score

64

↑

FairBetter than 99% of packages

Maintenance64

Regular maintenance activity

Popularity73

Solid adoption and visibility

Community41

Growing community involvement

Maturity65

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 ~360 days

Recently: every ~464 days

Total

14

Last Release

211d ago

Major Versions

v0.6.0 → v1.0.02019-07-11

v1.2.0 → 3.x-dev2025-10-19

PHP version history (4 changes)v0.2.6PHP &gt;=5.3.2

v0.4.0PHP &gt;=5.4.0

v0.4.1PHP &gt;=5.3.0

3.x-devPHP &gt;=7.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/147145?v=4)[Cees-Jan Kiewiet](/maintainers/WyriHaximus)[@WyriHaximus](https://github.com/WyriHaximus)

![](https://avatars.githubusercontent.com/u/776829?v=4)[Christian Lück](/maintainers/clue)[@clue](https://github.com/clue)

![](https://www.gravatar.com/avatar/5de14776bbddf901c6e24d35829fe66fe997c303d53aca83cc7d1a90bb0b7110?d=identicon)[jsor](/maintainers/jsor)

![](https://www.gravatar.com/avatar/3afcc18d00fff840775bbf9570b3e9cd3997ca4820b9bfb14caf6da3ae580370?d=identicon)[igorw](/maintainers/igorw)

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

---

Top Contributors

[![clue](https://avatars.githubusercontent.com/u/776829?v=4)](https://github.com/clue "clue (49 commits)")[![WyriHaximus](https://avatars.githubusercontent.com/u/147145?v=4)](https://github.com/WyriHaximus "WyriHaximus (39 commits)")[![cboden](https://avatars.githubusercontent.com/u/617694?v=4)](https://github.com/cboden "cboden (13 commits)")[![SimonFrings](https://avatars.githubusercontent.com/u/44357440?v=4)](https://github.com/SimonFrings "SimonFrings (12 commits)")[![jsor](https://avatars.githubusercontent.com/u/55574?v=4)](https://github.com/jsor "jsor (6 commits)")[![igorw](https://avatars.githubusercontent.com/u/88061?v=4)](https://github.com/igorw "igorw (6 commits)")[![krlv](https://avatars.githubusercontent.com/u/3404064?v=4)](https://github.com/krlv "krlv (3 commits)")[![whatthejeff](https://avatars.githubusercontent.com/u/306525?v=4)](https://github.com/whatthejeff "whatthejeff (1 commits)")[![e3betht](https://avatars.githubusercontent.com/u/1811561?v=4)](https://github.com/e3betht "e3betht (1 commits)")[![nhedger](https://avatars.githubusercontent.com/u/649677?v=4)](https://github.com/nhedger "nhedger (1 commits)")[![PaulRotmann](https://avatars.githubusercontent.com/u/85174210?v=4)](https://github.com/PaulRotmann "PaulRotmann (1 commits)")[![reedy](https://avatars.githubusercontent.com/u/67615?v=4)](https://github.com/reedy "reedy (1 commits)")

---

Tags

cachephpreactphppromisereactphpcachecaching

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[psr/simple-cache

Common interfaces for simple caching

8.1k727.3M2.1k](/packages/psr-simple-cache)[tedivm/stash

The place to keep your cache.

9824.8M124](/packages/tedivm-stash)[spatie/blink

Cache that expires in the blink of an eye

1685.0M8](/packages/spatie-blink)[gregwar/cache

A lightweight file-system cache system

1084.5M22](/packages/gregwar-cache)[putyourlightson/craft-blitz

Intelligent static page caching for creating lightning-fast sites.

153471.5k29](/packages/putyourlightson-craft-blitz)[tedivm/stash-bundle

Incorporates the Stash caching library into Symfony.

841.4M16](/packages/tedivm-stash-bundle)

PHPackages © 2026

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