PHPackages                             seanja/cacheable-trait - 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. seanja/cacheable-trait

ActiveLibrary[Caching](/categories/caching)

seanja/cacheable-trait
======================

simple generic cacheable trait

1.0.1(2y ago)029[1 PRs](https://github.com/SeanJA/cacheable-trait/pulls)1MITPHPPHP ^8.3CI passing

Since Apr 19Pushed 3mo agoCompare

[ Source](https://github.com/SeanJA/cacheable-trait)[ Packagist](https://packagist.org/packages/seanja/cacheable-trait)[ RSS](/packages/seanja-cacheable-trait/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (4)Versions (4)Used By (1)

cacheable-trait
===============

[](#cacheable-trait)

Simple configurable trait to add caching per-method.

How to use it:
--------------

[](#how-to-use-it)

---

##### Add use and pass in the psr6 cache item pool interface

[](#add-use-and-pass-in-the-psr6-cache-item-pool-interface)

```
class Controller
{
    use SeanJA\Cache\CacheableTrait;

    public function __construct(CacheItemPoolInterface $cache)
    {
      $this->setCache($cache);
    }
}
```

##### Using it in a method:

[](#using-it-in-a-method)

By default, this value will be remembered for 1 hour

```
    public function cacheableMethod( $cacheable_parameters )
    {
        $data = $this->remember(function(){
            return 'Cacheable data';
        });

        return response($data);
    }
```

##### Configure TTL (per class)

[](#configure-ttl-per-class)

Add a protected method called `getTTL` to your class that returns a custom date interval based on the input

```
    protected function getTTL(string $method, array $args): DateInterval
    {
        return match ($method) {
            'method1' => DateInterval::createFromDateString('1 day'),
            'method2' => DateInterval::createFromDateString('10 seconds'),
            'method3' => DateInterval::createFromDateString('10 seconds'),
            default => DateInterval::createFromDateString('6 minutes'),
        };
    }
```

##### Implement your own key (per class)

[](#implement-your-own-key-per-class)

You can change the way the key is generated, it should be unique for each place you use remember otherwise you will end up overwriting things in weird ways

```
    protected function generateCacheKey(string $class, string $method, array $args): string
    {
        return 'key';
    }
```

##### Add a custom id to the cache (per class)

[](#add-a-custom-id-to-the-cache-per-class)

Add a custom value to the cache, can be used to bust the cache when you do a deploy, or you could set it manually to bust the cache at any point.

```
    protected function getCacheId(): string
    {
        return $_ENV['RELEASE_VERSION'];
    }
```

##### Decide if something should be cached (per class)

[](#decide-if-something-should-be-cached-per-class)

Can be used to avoid caching certain method calls

```
    protected function shouldCache(string $method, array $args): bool
    {
        return $method === 'maybeCache', $args[0] === 'plz cache';
    }
```

##### Disable the cache (remember will now do nothing because the cache is null)

[](#disable-the-cache-remember-will-now-do-nothing-because-the-cache-is-null)

This will disable caching for the class until you restore it

```
    public function shouldDisableCaching(): void
    {
        $this->disableCache();
    }
```

##### Disable the cache temporarily

[](#disable-the-cache-temporarily)

If you really want to

```
class CachedClass{
    use \SeanJA\Cache\CacheableTrait;

    public function cachedTime(){
        return $this->remember(function(){
            return time();
        });
    }

    public function uncachedTime(): void
    {
        $this->disableCache();
        $data = $this->cachedTime();
        $this->restoreCache();
        return $data;
    }
}
```

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance53

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity62

Established project with proven stability

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

Total

2

Last Release

778d ago

PHP version history (2 changes)1.0.0PHP ^8

1.0.1PHP ^8.3

### Community

Maintainers

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

---

Top Contributors

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

---

Tags

cachecachingpsr6psr-6

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/seanja-cacheable-trait/health.svg)

```
[![Health](https://phpackages.com/badges/seanja-cacheable-trait/health.svg)](https://phpackages.com/packages/seanja-cacheable-trait)
```

###  Alternatives

[symfony/cache

Provides extended PSR-6, PSR-16 (and tags) implementations

4.2k348.9M2.5k](/packages/symfony-cache)[tedivm/stash

The place to keep your cache.

9824.8M124](/packages/tedivm-stash)[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)[cache/adapter-common

Common classes for PSR-6 adapters

11124.4M38](/packages/cache-adapter-common)[cache/tag-interop

Framework interoperable interfaces for tags

10525.0M12](/packages/cache-tag-interop)[cache/hierarchical-cache

A helper trait and interface to your PSR-6 cache to support hierarchical keys.

6016.1M11](/packages/cache-hierarchical-cache)

PHPackages © 2026

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