PHPackages                             friendsofhyperf/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. friendsofhyperf/cache

ActiveLibrary[Caching](/categories/caching)

friendsofhyperf/cache
=====================

The cache component for Hyperf.

v3.2.1(3w ago)240.8k↓28%1MITPHP

Since May 21Pushed 2w ago1 watchersCompare

[ Source](https://github.com/friendsofhyperf/cache)[ Packagist](https://packagist.org/packages/friendsofhyperf/cache)[ Fund](https://hdj.me/sponsors/)[ GitHub Sponsors](https://github.com/huangdijia)[ RSS](/packages/friendsofhyperf-cache/feed)WikiDiscussions main Synced today

READMEChangelog (10)Dependencies (14)Versions (131)Used By (0)

Cache
=====

[](#cache)

[中文说明](README_CN.md)

Introduction
------------

[](#introduction)

`friendsofhyperf/cache` wraps the drivers provided by `hyperf/cache` with a Laravel-style repository API. It supports PSR-16 operations, named stores, facade access, cache events, macros, and stale-while-revalidate caching.

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

[](#installation)

```
composer require friendsofhyperf/cache
```

The component requires Hyperf 3.2. Its `ConfigProvider` registers `FriendsOfHyperf\Cache\Contract\Factory` and `FriendsOfHyperf\Cache\Contract\Repository` in the container.

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

[](#configuration)

This component does not publish a separate configuration file. Configure drivers and named stores through `hyperf/cache`; `CacheManager::store($name)`passes the name to Hyperf's cache manager. The default repository resolves the `default` store.

Accessing a Repository
----------------------

[](#accessing-a-repository)

### Dependency Injection

[](#dependency-injection)

Inject `Contract\Repository` for the default store:

```
namespace App\Controller;

use FriendsOfHyperf\Cache\Contract\Repository;

class IndexController
{
    public function __construct(private Repository $cache)
    {
    }

    public function index(): mixed
    {
        return $this->cache->remember('users', 60, function () {
            return [];
        });
    }
}
```

Inject `Contract\Factory` when a named store is required:

```
use FriendsOfHyperf\Cache\Contract\Factory;

$cache = $factory->store('redis');
```

### Facade

[](#facade)

```
use FriendsOfHyperf\Cache\Facade\Cache;

$users = Cache::remember('users', 60, function () {
    return [];
});

$users = Cache::store('redis')->get('users');
```

`Cache::driver($name)` is an alias of `Cache::store($name)`. `Cache::resolve($name)` creates a new repository instead of returning the manager's cached repository instance.

Core Operations
---------------

[](#core-operations)

The repository implements `Psr\SimpleCache\CacheInterface`, so `get()`, `set()`, `delete()`, `clear()`, `getMultiple()`, `setMultiple()`, `deleteMultiple()`, and `has()` are available. It also provides these extensions:

MethodBehavior`get($key, $default = null)`Retrieves one item; a callable default is evaluated on a miss. Passing an array delegates to `many()`.`put($key, $value, $ttl = null)`Stores one item; `null` means forever and a non-positive TTL deletes the key. Passing an associative array delegates to `putMany()`, with the second argument used as its TTL.`putMany($values, $ttl = null)`Stores multiple items; a non-positive TTL deletes their keys.`forever($key, $value)`Stores one item without a TTL.`add($key, $value, $ttl = null)`Stores the item only when `get($key)` returns `null`.`many($keys)`Retrieves multiple keys; associative input may provide per-key defaults.`pull($key, $default = null)`Retrieves and then deletes an item.`remember($key, $ttl, Closure $callback)`Returns the cached value or stores the callback result with a TTL.`rememberForever($key, Closure $callback)` / `sear(...)`Returns the cached value or stores the callback result forever.`increment($key, $value = 1)` / `decrement(...)`Reads, adjusts, and stores an integer value without a TTL.`flush()`Alias of `clear()`.`missing($key)`Inverse of `has($key)`.`getDriver()` / `getStore()`Returns the underlying Hyperf `DriverInterface`.TTL values accepted by the extended repository methods may be seconds, `DateInterval`, or `DateTimeInterface`.

::: warning Behavioral boundaries The repository treats a cached `null` as a miss. `add()`, `pull()`, and the increment/decrement methods are implemented as separate operations, so they are not atomic. Although `pull()` accepts a `$default` argument, the current implementation does not pass it to `get()` and returns `null` for a missing key. :::

Stale-While-Revalidate
----------------------

[](#stale-while-revalidate)

`flexible()` accepts a two-item TTL array: the first value is the fresh period and the second is the storage TTL used for both the cached value and its internal creation timestamp.

```
use FriendsOfHyperf\Cache\Facade\Cache;

$users = Cache::flexible('users', [30, 300], function () {
    return [];
}, [
    'seconds' => 10,
    'owner' => 'users-refresh',
]);
```

On a miss, the callback runs immediately. During the fresh period, the cached value is returned. After the fresh period, the stale value is returned and a deferred callback attempts to refresh it under a lock. A refresh is skipped if another process has already updated the creation timestamp.

Install both optional dependencies before using `flexible()`:

```
composer require friendsofhyperf/lock hyperf/coroutine
```

The optional lock array accepts `seconds` and `owner`; they default to `0` and `null`.

Events
------

[](#events)

When the container provides `Psr\EventDispatcher\EventDispatcherInterface`, the repository dispatches events for reads, writes, deletes, and flushes:

- `CacheHit`, `CacheMissed`, `RetrievingKey`, `RetrievingManyKeys`
- `WritingKey`, `WritingManyKeys`, `KeyWritten`, `KeyWriteFailed`
- `ForgettingKey`, `KeyForgotten`, `KeyForgetFailed`
- `CacheFlushing`, `CacheFlushed`

Each event includes the store name. Single-key events also include the key, write events expose the value and TTL where applicable, and bulk events expose their keys; `WritingManyKeys` also exposes the values. Bulk reads additionally dispatch `CacheHit` or `CacheMissed` for each returned key.

Reference
---------

[](#reference)

The API is inspired by Laravel Cache, but behavior should be verified against this component's contracts and implementation.

###  Health Score

55

↑

FairBetter than 97% of packages

Maintenance96

Actively maintained with recent releases

Popularity32

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 99% of commits — single point of failure

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

Recently: every ~47 days

Total

130

Last Release

25d ago

Major Versions

v2.0.3 → v3.0.0-beta42022-05-24

v2.0.11 → v3.0.0-beta222022-06-24

v2.0.19 → v3.0.0-rc.162022-09-21

v2.0.24 → v3.0.02023-01-02

v2.0.28 → v3.0.62023-01-30

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/8337659?v=4)[Deeka Wong](/maintainers/huangdijia)[@huangdijia](https://github.com/huangdijia)

---

Top Contributors

[![huangdijia](https://avatars.githubusercontent.com/u/8337659?v=4)](https://github.com/huangdijia "huangdijia (98 commits)")[![szutoutou](https://avatars.githubusercontent.com/u/17758819?v=4)](https://github.com/szutoutou "szutoutou (1 commits)")

---

Tags

hyperfv3.2

### Embed Badge

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

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

###  Alternatives

[hyperf/database

A flexible database library.

192.9M324](/packages/hyperf-database)[hyperf/validation

hyperf validation

122.2M200](/packages/hyperf-validation)[hyperf/http-server

A HTTP Server for Hyperf.

103.0M373](/packages/hyperf-http-server)[hyperf/crontab

A crontab component for Hyperf.

131.7M77](/packages/hyperf-crontab)[hyperf/amqp

A amqplib for hyperf.

231.3M73](/packages/hyperf-amqp)[limingxinleo/hyperf-utils

Utils for Hyperf.

29137.1k3](/packages/limingxinleo-hyperf-utils)

PHPackages © 2026

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