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

ActiveLibrary[Caching](/categories/caching)

fuwasegu/cache-decorator
========================

A decorator for caching the results of method calls on any instance, supporting pure functions only.

1.2.0(1y ago)67MITPHPPHP ^8.1

Since Oct 4Pushed 1y ago1 watchersCompare

[ Source](https://github.com/fuwasegu/cache-decorator)[ Packagist](https://packagist.org/packages/fuwasegu/cache-decorator)[ RSS](/packages/fuwasegu-cache-decorator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (5)Versions (4)Used By (0)

Cache Decorator
===============

[](#cache-decorator)

[![Coverage Status](https://camo.githubusercontent.com/ecee5ffbbfaa7da432b32e9c758e6f1940e6fb2a27d1a8378c84ec728eabb597/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f66757761736567752f63616368652d6465636f7261746f722f62616467652e7376673f6272616e63683d6d61696e)](https://coveralls.io/github/fuwasegu/cache-decorator?branch=main)[![MIT License](https://camo.githubusercontent.com/db79b92834d905629b1aea42c9aa493da02060189e2af90840b1be5d6bf6ddf7/687474703a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c6174)](LICENSE)

A PHP library for implementing a cache decorator pattern, allowing easy caching of method results.

Requirements
------------

[](#requirements)

- PHP 8.1 or higher

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

[](#installation)

You can install the package via composer:

```
composer require fuwasegu/cache-decorator
```

Usage
-----

[](#usage)

Caution

Since serialization costs can be high, caching should primarily be applied to I/O bottleneck scenarios, such as HTTP communication and relational database interactions. It is also useful for computationally expensive algorithms (e.g., full search).

Moreover, the caching driver should utilize lighter options like Redis or Memcached instead of relying on the heavier I/O operations to achieve expected performance improvements.

Here's a basic example of how to use the cache decorator:

```
use Fuwasegu\CacheDecorator;
use Some\CacheImplementation;

class ExpensiveOperation
{
    #[Pure]
    public function heavyComputation($param)
    {
        // Some expensive operation
        sleep(5);
        return "Result for $param";
    }
}

$cacheImplementation = new CacheImplementation();
$decorator = CacheDecorator::wrap(new ExpensiveOperation(), $cacheImplementation);

// First call will be slow
$result1 = $decorator->heavyComputation('test');

// Second call will be fast, returning cached result
$result2 = $decorator->heavyComputation('test');
```

Only pure methods can be cached. In order to mark a method as pure, use the `#[Pure]` attribute, not the `#[Pure]` attribute provided by PhpStorm.

Note

The advantage of this library is that, since CacheDecorator::class internally utilizes Generics and Mixin, developers can wrap any instance without losing the experience, as the methods of the wrapped instance are still auto-completed in the IDE from the CacheDecorator instance.

### Setting TTL globally

[](#setting-ttl-globally)

CacheDecorator class has a static property `$defaultTtl`, so you can set the default TTL by calling `CacheDecorator::setDefaultTtl($ttl)` before wrapping the instance. This default value will be used in constructors of CacheDecorator.

```
CacheDecorator::setDefaultTtl(3600);

$decorator = CacheDecorator::wrap($someInstance, $cacheImplementation);

// the result will be cached for 3600 seconds.
$decorator->someMethod();
```

### Especially in Laravel

[](#especially-in-laravel)

In Laravel, you can use `Illuminate\Cache\Repository` as the cache implementation.

```
class SampleController
{
    public function __construct(
        private Illuminate\Cache\Repository $cache,
    ) {}

    public function __index(): Response
    {
        $decorator = CacheDecorator::wrap(new ExpensiveOperation(), $this->cache);

        $result = $decorator->heavyComputation('test');
    }
}
```

### Supporting multiple cache implementations

[](#supporting-multiple-cache-implementations)

The `CacheDecorator::wrap()` method supports both PSR-16 SimpleCache and PSR-6 Cache interfaces. This means you can use either `Psr\SimpleCache\CacheInterface` or `Psr\Cache\CacheItemPoolInterface` implementations as the cache backend.

Example:

```
// Using PSR-16 SimpleCache
$psr16Cache = new SomePsr16CacheImplementation();
$decorator = CacheDecorator::wrap(new ExpensiveOperation(), $psr16Cache);

// Using PSR-6 Cache
$psr6Cache = new SomePsr6CacheImplementation();
$decorator = CacheDecorator::wrap(new ExpensiveOperation(), $psr6Cache);
```

This flexibility allows you to use the cache implementation that best fits your project's needs.

#### FYI

[](#fyi)

- [PSR-16 SimpleCache](https://www.php-fig.org/psr/psr-16/)
- [PSR-16 GitHub](https://github.com/php-fig/simple-cache)
- [PSR-6 Cache](https://www.php-fig.org/psr/psr-6/)
- [PSR-6 GitHub](https://github.com/php-fig/cache)

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~1 days

Total

3

Last Release

580d ago

### Community

Maintainers

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

---

Top Contributors

[![fuwasegu](https://avatars.githubusercontent.com/u/52437973?v=4)](https://github.com/fuwasegu "fuwasegu (27 commits)")

---

Tags

phpcacheDecoratoro

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[laminas/laminas-cache

Caching implementation with a variety of storage options, as well as codified caching strategies for callbacks, classes, and output

1076.9M130](/packages/laminas-laminas-cache)[voku/simple-cache

Simple Cache library

322.5M7](/packages/voku-simple-cache)[infocyph/intermix

A Collection of useful PHP class functions.

136.4k1](/packages/infocyph-intermix)

PHPackages © 2026

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