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

ActiveLibrary[Caching](/categories/caching)

italystrap/cache
================

Simple PSR-16 cache implementations for WordPress transient the OOP way

2.0.0(2y ago)625.8k—9.4%1MITPHPPHP &gt;=7.4CI passing

Since Mar 3Pushed 2mo ago1 watchersCompare

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

READMEChangelog (2)Dependencies (23)Versions (3)Used By (0)

ItalyStrap Cache API
====================

[](#italystrap-cache-api)

[![Build status](https://github.com/ItalyStrap/cache/actions/workflows/test.yml/badge.svg)](https://github.com/ItalyStrap/cache/actions/workflows/test.yml?query=workflow%3Atest)[![Latest Stable Version](https://camo.githubusercontent.com/5b60b476839bbfa77ed727cabab706ada9271373c089ffd125f00cb1d480d769/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6974616c7973747261702f63616368652e737667)](https://packagist.org/packages/italystrap/cache)[![Total Downloads](https://camo.githubusercontent.com/cdb62d98114bba0885d247acaa8db0aa97bc7b1899f1225cb70cc66d5878bc32/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6974616c7973747261702f63616368652e737667)](https://packagist.org/packages/italystrap/cache)[![Latest Unstable Version](https://camo.githubusercontent.com/12657ecaf48575cbf3135f2179a8309d9cf492b652557405d8c0cfbe47de61cc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f767072652f6974616c7973747261702f63616368652e737667)](https://packagist.org/packages/italystrap/cache)[![License](https://camo.githubusercontent.com/6129f484895dc4e789b641259d2fc8b48b95cf4cbffff9c2a20df7f4c256388c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6974616c7973747261702f63616368652e737667)](https://packagist.org/packages/italystrap/cache)[![PHP from Packagist](https://camo.githubusercontent.com/5702af42daab8f341430b52aa86f7a3e18aabf6764aa5470a17f8fce7a71ed48/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6974616c7973747261702f6361636865)](https://camo.githubusercontent.com/5702af42daab8f341430b52aa86f7a3e18aabf6764aa5470a17f8fce7a71ed48/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6974616c7973747261702f6361636865)[![Mutation testing badge](https://camo.githubusercontent.com/902d35f6177367c59fdb61a0e72560e49403fe1bcdfdb4cc0339e213f694ab37/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f7374796c653d666c61742675726c3d687474707325334125324625324662616467652d6170692e737472796b65722d6d757461746f722e696f2532466769746875622e636f6d2532464974616c79537472617025324663616368652532466d6173746572)](https://dashboard.stryker-mutator.io/reports/github.com/ItalyStrap/cache/master)

PSR-16 &amp; PSR-6 Cache implementations for WordPress transient and cache the OOP way

**Version 2.0 is a BC breaks please read the following documentation**

Table Of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Basic Usage](#basic-usage)
- [Advanced Usage](#advanced-usage)
- [Contributing](#contributing)
- [License](#license)
- [Credits](#credits)

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

[](#installation)

The best way to use this package is through Composer:

```
composer require italystrap/cache
```

This package adheres to the [SemVer](http://semver.org/) specification and will be fully backward compatible between minor versions.

For more information about the WordPress API:

- [WordPress Transients API docs](https://developer.wordpress.org/apis/transients/)
- [WordPress Cache API docs](https://developer.wordpress.org/reference/classes/wp_object_cache/)

Why this package?
-----------------

[](#why-this-package)

Initially I created this package to use the [PSR-16](https://www.php-fig.org/psr/psr-16/) cache interface in WordPress, but starting from this issue [\#4](https://github.com/ItalyStrap/cache/issues/4) I decided to extract the drivers and also add the [PSR-6](https://www.php-fig.org/psr/psr-6/) cache interface too.

From version 2.0 I also added the PSR-6 implementation, so you can also use the `Pool` class to cache your data if you need it.

So this package now support both the [PSR-16](https://www.php-fig.org/psr/psr-16/) and [PSR-6](https://www.php-fig.org/psr/psr-6/) cache interfaces.

The driver required by this package uses the Transients and Object Cache APIs from WordPress to store the data, but if you need to use other APIs, you can create your own driver because just implements the interface `\ItalyStrap\Storage\CacheInterface` from [Storage API](https://github.com/ItalyStrap/storage).

### Moving from Version 1 to Version 2

[](#moving-from-version-1-to-version-2)

The first important thing is from the version 2 you need to pass the driver object and the expiration object to the constructor of the class you want to use.

`SimpleCache` and `Pool` are the two classes that need the driver and the expiration to be passed to the constructor.

The driver is an object wrapper for the WordPress Transient API and the WordPress Object Cache API.

The expiration object is used to set the expiration time of the cache.

Below in the documentation you will find the name of the drivers that you can use and the expiration object.

The second important thing is that the driver must implement the `CacheInterface` from [Cache API](https://github.com/ItalyStrap/storage), this way if you need to create your own driver you can do it simply by implementing the interface.

### Why the needs of an Expiration object?

[](#why-the-needs-of-an-expiration-object)

The expiration object is used to set the expiration time of the cache.

Because I want to be as close as possible to the PSR-16 and PSR-6 specifications, I have created an object that is responsible for setting the expiration time, this way I can reuse the same logic across all PSR-16 and PSR-6 implementations and I didn't need to create more methods that are not in the specifications.

Basic Usage
-----------

[](#basic-usage)

### Timer constants

[](#timer-constants)

Inside WordPress there are some constants that can be used to express time in seconds. Here is a list of them:

```
const MINUTE_IN_SECONDS  = 60; // (seconds)
const HOUR_IN_SECONDS    = 60 * MINUTE_IN_SECONDS;
const DAY_IN_SECONDS     = 24 * HOUR_IN_SECONDS;
const WEEK_IN_SECONDS    = 7 * DAY_IN_SECONDS;
const MONTH_IN_SECONDS   = 30 * DAY_IN_SECONDS;
const YEAR_IN_SECONDS    = 365 * DAY_IN_SECONDS;
```

Or you can use the built-in constant from `ItalyStrap\Cache\ExpirationInterface`:

```
use ItalyStrap\Cache\ExpirationInterface;

$expirationTime = ExpirationInterface::MINUTE_IN_SECONDS;
$expirationTime = ExpirationInterface::HOUR_IN_SECONDS;
$expirationTime = ExpirationInterface::DAY_IN_SECONDS;
$expirationTime = ExpirationInterface::WEEK_IN_SECONDS;
$expirationTime = ExpirationInterface::MONTH_IN_SECONDS;
$expirationTime = ExpirationInterface::YEAR_IN_SECONDS;
```

Or you can use the built-in PHP function `strtotime()` to express time in seconds.

### Common usage with builtin WordPress Transients API

[](#common-usage-with-builtin-wordpress-transients-api)

```
if (false === ($special_data_to_save = \get_transient('special_data_to_save'))) {
    // It wasn't there, so regenerate the data and save the transient
    $special_data_to_save = ['some-key' => 'come value'];
    \set_transient('special_data_to_save', $special_data_to_save, 12 * HOUR_IN_SECONDS);
}
```

The data you can save can be anything that is supported by the [Serialization API](https://developer.wordpress.org/reference/functions/maybe_serialize/). In short, you can save any scalar value, array, object.

### Common usage with the Pool cache

[](#common-usage-with-the-pool-cache)

```
use ItalyStrap\Cache\Pool;
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()
$expiration = new Expiration();

$pool = new Pool($driver, $expiration);

// Pass the pool object to other classes that need to save data
// then retrieve the data from the pool
$item = $pool->getItem('special_data_to_save');
if (!$item->isHit()) {
    // It wasn't there, so regenerate the data and save the transient
    $item->set(['some-key' => 'some value']);
    $item->expiresAfter(12 * HOUR_IN_SECONDS);
    $pool->save($item);
}
$special_data_to_save = $item->get();

['some-key' => 'some value'] === $special_data_to_save; // True
```

### Common usage with the SimpleCache

[](#common-usage-with-the-simplecache)

Only if you need to parse binary data (as for example image files) you can use the `BinaryCacheDecorator` class, but remember that if the file is more than 1MB it is better to not use this to save in the database.

And because you are a good developer, you will not save binary data in the database, and you will use the `Transient` class instead of the `BinaryCacheDecorator` class.

```
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Cache\SimpleCache;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()

$expiration = new Expiration();
$cache = new SimpleCache($driver, $expiration);

// Pay attention to `SimpleCacheInterface::get()` method because if there is no value will return `null` and not `false` as the WordPress Transient API does.
if (null === ($special_data_to_save = $cache->get('special_data_to_save'))) {
    // It wasn't there, so regenerate the data and save the transient
    $special_data_to_save = ['some-key' => 'some value'];
    $cache->set('special_data_to_save', $special_data_to_save, 12 * HOUR_IN_SECONDS);
}

['some-key' => 'some value'] === $special_data_to_save; // True
```

### Deleting cache with Pool

[](#deleting-cache-with-pool)

```
use ItalyStrap\Cache\Pool;
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()
$expiration = new Expiration();

$pool = new Pool($driver, $expiration);

$item = $pool->getItem('special_data_to_save');
$item->set(['some-key' => 'some value']);
$item->expiresAfter(12 * HOUR_IN_SECONDS);
$pool->save($item);

$pool->deleteItem('special_data_to_save'); // Return bool

// `::getItem()` will return a new item instance, always
$pool->getItem('special_data_to_save')->isHit(); // Return false
```

### Deleting cache with SimpleCache

[](#deleting-cache-with-simplecache)

```
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Cache\SimpleCache;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()

$expiration = new Expiration();
$cache = new SimpleCache($driver, $expiration);

$cache->set('special_data_to_save', ['some-key' => 'some value'], 12 * HOUR_IN_SECONDS);

$cache->delete('special_data_to_save'); // Return bool

$cache->get('special_data_to_save'); // Return null
```

### Check cache exists with Pool

[](#check-cache-exists-with-pool)

```
use ItalyStrap\Cache\Pool;
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()
$expiration = new Expiration();

$pool = new Pool($driver, $expiration);

$item = $pool->getItem('special_data_to_save');
$item->set(['some-key' => 'some value']);
$item->expiresAfter(12 * HOUR_IN_SECONDS);
$pool->save($item);

$pool->hasItem('special_data_to_save'); // Return true

// But also this will return false if the item is expired or not exists
$pool->hasItem('expired_or_not_existent_value'); // Return false
```

### Check cache exists with SimpleCache

[](#check-cache-exists-with-simplecache)

```
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Cache\SimpleCache;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()

$expiration = new Expiration();
$cache = new SimpleCache($driver, $expiration);

$cache->set('special_data_to_save', ['some-key' => 'some value'], 12 * HOUR_IN_SECONDS);
$cache->has('special_data_to_save'); // Return true

// But also this will return false if the item is expired or not exists
$cache->has('expired_or_not_existent_value'); // Return false
```

### Saving multiple cache with SimpleCache

[](#saving-multiple-cache-with-simplecache)

```
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Cache\SimpleCache;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()

$expiration = new Expiration();
$cache = new SimpleCache($driver, $expiration);

$values = [
    'key'       => 'value',
    'key2'      => 'value2',
];

$cache->setMultiple($values, 12 * HOUR_IN_SECONDS); // Return bool
```

### Fetching multiple cache with SimpleCache

[](#fetching-multiple-cache-with-simplecache)

```
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Cache\SimpleCache;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()

$expiration = new Expiration();
$cache = new SimpleCache($driver, $expiration);

$values = [
    'key'       => 'value',
    'key2'      => 'value2',
    'key3'      => false, // This will be replaced with 'some default value' because the method pass a default value
];

$fetched_values = $cache->getMultiple(\array_keys($values), 'some default value'); // Return values
```

### Deleting multiple cache with SimpleCache

[](#deleting-multiple-cache-with-simplecache)

```
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Cache\SimpleCache;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()

$expiration = new Expiration();
$cache = new SimpleCache($driver, $expiration);

$values = [
    'key'       => 'value',
    'key2'      => 'value2',
    'key3'      => false,
];

$cache->deleteMultiple(\array_keys($values)); // Return bool
```

### Clearing cache with SimpleCache

[](#clearing-cache-with-simplecache)

This method do not clear the entire WordPress cache, only the cache used by client with ::set() and ::setMultiple() methods.

```
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Cache\SimpleCache;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()

$expiration = new Expiration();
$cache = new SimpleCache($driver, $expiration);
$cache->set('special_data_to_save',['some-key' => 'come value'], 12 * HOUR_IN_SECONDS);

$values = [
    'key'       => 'value',
    'key2'      => 'value2',
];

$cache->setMultiple($values, 12 * HOUR_IN_SECONDS);

$cache->clear(); // Return bool

$cache->get('special_data_to_save'); // Return null
$cache->get('key'); // Return null
$cache->get('key2'); // Return null
```

Cache::clear() will flush 'special\_data\_to\_save', 'key' and 'key2'.

Other examples
--------------

[](#other-examples)

```
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Cache\SimpleCache;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()

$expiration = new Expiration();
$cache = new SimpleCache($driver, $expiration);

// Get any existing copy of our transient data
if (false === ($special_data_to_save = $cache->get('special_data_to_save'))) {
    // It wasn't there, so regenerate the data and save the transient
     $cache->set('special_data_to_save', ['some-key' => 'some value'], 12 * HOUR_IN_SECONDS);
}
// Use the data like you would have normally...

//Or

// Get any existing copy of our transient data
if (!$cache->has('special_data_to_save')) {
    // It wasn't there, so regenerate the data and save the transient
     $cache->set('special_data_to_save', ['some-key' => 'some value'], 12 * HOUR_IN_SECONDS);
}
// Use the data like you would have normally...
```

You could also use a Bridge to use the \\Psr\\SimpleCache\\CacheInterface and inject the \\Psr\\Cache\\CacheItemPoolInterface

```
use ItalyStrap\Cache\Pool;
use ItalyStrap\Cache\Expiration;
use ItalyStrap\Storage\BinaryCacheDecorator;
use ItalyStrap\Storage\Transient;

$driver = new BinaryCacheDecorator(new Transient()); // Or use new Cache()
$expiration = new Expiration();

$pool = new Pool($driver, $expiration);

$cache = new \ItalyStrap\Cache\SimpleCacheBridge($pool);
// and use the $cache as \Psr\SimpleCache\CacheInterface
```

### Use the Factory to simplify the creation of the Cache

[](#use-the-factory-to-simplify-the-creation-of-the-cache)

```
use ItalyStrap\Cache\Factory;

$cache = (new Factory())->makePool();
$cache = (new Factory())->makePoolTransient();
$cache = (new Factory())->makeSimpleCache();
$cache = (new Factory())->makeSimpleCacheTransient();
$cache = (new Factory())->makeSimpleCacheBridge();
$cache = (new Factory())->makeSimpleCacheBridgeTransient();
```

Contributing
------------

[](#contributing)

All feedback / bug reports / pull requests are welcome.

License
-------

[](#license)

Copyright (c) 2019 Enea Overclokk, ItalyStrap

This code is licensed under the [MIT](LICENSE).

Credits
-------

[](#credits)

- [DoctrineSimpleCache](https://github.com/Roave/DoctrineSimpleCache)
- [PHP Cache organisation](https://github.com/php-cache/integration-tests)

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance57

Moderate activity, may be stable

Popularity34

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 94.9% 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 ~1173 days

Total

2

Last Release

1094d ago

Major Versions

1.0.0 → 2.0.02023-05-20

PHP version history (2 changes)1.0.0PHP &gt;=7.2

2.0.0PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/13d145319a065be260ee79e728655780ddd63002e5ac6c317701c8996ec8d94c?d=identicon)[overclokk](/maintainers/overclokk)

---

Top Contributors

[![overclokk](https://avatars.githubusercontent.com/u/4604932?v=4)](https://github.com/overclokk "overclokk (37 commits)")[![widoz](https://avatars.githubusercontent.com/u/1917784?v=4)](https://github.com/widoz "widoz (2 commits)")

---

Tags

cachephppsr-16psr-6psr-6-psr-16wordpresswordpress-php-librarypsrwordpresscachepsr-16psr-6transienttransients

###  Code Quality

Static AnalysisPsalm, Rector

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

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

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

###  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)[cache/simple-cache-bridge

A PSR-6 bridge to PSR-16. This will make any PSR-6 cache compatible with SimpleCache.

423.1M27](/packages/cache-simple-cache-bridge)[codeigniter4/cache

PSR-6 and PSR-16 Cache Adapters for CodeIgniter 4

1320.1k](/packages/codeigniter4-cache)

PHPackages © 2026

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