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

ActiveLibrary[Caching](/categories/caching)

charcoal/cache
==============

Charcoal service provider for the Stash Cache Library

v5.0.0(2y ago)0983MITPHPPHP ^7.4 || ^8.0

Since May 7Pushed 2y ago2 watchersCompare

[ Source](https://github.com/charcoalphp/cache)[ Packagist](https://packagist.org/packages/charcoal/cache)[ Docs](https://locomotivemtl.github.io/charcoal-config/)[ RSS](/packages/charcoal-cache/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (9)Versions (38)Used By (3)

Charcoal Cache
==============

[](#charcoal-cache)

The Cache package provides an integration with [Stash](https://github.com/tedious/Stash) for caching the results of expensive tasks.

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

[](#installation)

```
composer require charcoal/cache
```

For Charcoal projects, the service provider can be registered from your configuration file:

```
{
    "service_providers": {
        "charcoal/cache/service-provider/cache": {}
    }
}
```

Overview
--------

[](#overview)

### Service Provider

[](#service-provider)

#### Parameters

[](#parameters)

- **cache/available-drivers**: Collection of registered cache drivers that are supported by this system (via [`Stash\DriverList`](https://github.com/tedious/Stash/blob/v0.14.2/src/Stash/DriverList.php)).

#### Services

[](#services)

- **cache/config**: Configuration object for the caching service.
    See [Pool Configuration](#pool-configuration) for available options.
- **cache/drivers**: Collection of cache driver instances (as a service container) which uses `cache/available-drivers`.
    These drivers are pre-configured:
    - **file**: [FileSystem](https://www.stashphp.com/Drivers.html#filesystem)
    - **db**: [SQLite](https://www.stashphp.com/Drivers.html#sqlite)
    - **apc**: [APC](https://www.stashphp.com/Drivers.html#apc)
    - **memcache**: [Memcached](https://www.stashphp.com/Drivers.html#memcached)
    - **redis**: [Redis](https://www.stashphp.com/Drivers.html#redis)
    - **memory**: [Ephemeral](https://www.stashphp.com/Drivers.html#ephemeral) (Runtime Only)
    - **noop**: Blackhole (NULL caching driver)
- **cache/builder**: Instance of [`CacheBuilder`](src/Charcoal/Cache/CacheBuilder.php) that is used to build a cache pool.
- **cache/driver**: Reference to the Stash cache driver used by `cache`. Defaults to "memory".
- **cache**: Main instance of the Stash cache pool which uses `cache/driver` and `cache/config.prefix`.

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

[](#configuration)

### Pool Configuration

[](#pool-configuration)

Each pool comes with a set of default options which can be individually overridden.

SettingTypeDefaultDescription**active**`boolean``TRUE`Whether to enable or disable the cache service.**prefix**`string``charcoal`Name of the main Stash pool.**types**`string[]``memory`List of cache drivers to choose from for the main Stash pool. Defaults to "memory".**default\_ttl**`integer`1 weekDefault time-to-live (in seconds) for a cached item. Currently, only used by the APC driver (`cache/drivers.apc`).```
use Charcoal\Cache\CacheConfig;
use Charcoal\Cache\ServiceProvider\CacheServiceProvider;

$container->register(new CacheServiceProvider());

$container['cache/config'] = new CacheConfig([
    'prefix' => 'foobar',
    'types'  => [ 'apc', 'memcache', 'redis' ],
]);
```

### Driver Configuration

[](#driver-configuration)

Each driver comes with a set of default options which can be individually overridden.

—N/A—

Usage
-----

[](#usage)

Just fetch the default cache pool service:

```
$pool = $this->container->get('cache');
```

Or a custom-defined cache pool:

```
// Create a Stash pool with the Memcached driver and a custom namespace.
$pool1 = $this->container->get('cache/builder')->build('memcache', 'altcache');

// Create a custom Stash pool with the FileSystem driver and custom features.
$pool2 = $this->container->get('cache/builder')->build('file', [
    'namespace'  => 'mycache',
    'logger'     => $this->container->get('logger.custom_logger'),
    'pool_class' => \MyApp\Cache\Pool::class,
    'item_class' => \MyApp\Cache\Item::class,
]);

// Create a Stash pool with the "memory" cache driver.
$pool3 = new \Stash\Pool($container['cache/drivers']['memory']);
```

Then you can use the cache service directly:

```
// Get a Stash object from the cache pool.
$item = $pool->getItem("/user/{$userId}/info");

// Get the data from it, if any happens to be there.
$userInfo = $item->get();

// Check to see if the cache missed, which could mean that it either
// didn't exist or was stale.
if ($item->isMiss()) {
    // Run the relatively expensive code.
    $userInfo = loadUserInfoFromDatabase($userId);

    // Set the new value in $item.
    $item->set($userInfo);

    // Store the expensive code so the next time it doesn't miss.
    $pool->save($item);
}

return $userInfo;
```

See the [Stash documentation](stash-docs) for more information on using the cache service.

### Middleware

[](#middleware)

The [`CacheMiddleware`](src/Charcoal/Cache/Middleware/CacheMiddleware.php) is available for PSR-7 applications that support middleware. The middleware saves the HTTP response body and headers into a [PSR-6 cache pool](psr-6) and returns that cached response if still valid.

If you are using [charcoal/app](https://github.com/charcoalphp/app), you can add the middleware via the application configset:

```
"middlewares": {
    "charcoal/cache/middleware/cache": {
        "active": true,
        "methods": [ "GET", "HEAD" ]
    }
}
```

Otherwise, with [Slim](https://github.com/slimphp/slim), for example:

```
use Charcoal\Cache\Middleware\CacheMiddleware;
use Slim\App;
use Stash\Pool;

$app = new App();

// Register middleware
$app->add(new CacheMiddleware([
    'cache'   => new Pool(),
    'methods' => [ 'GET', 'HEAD' ],
]));
```

The middleware comes with a set of default options which can be individually overridden.

SettingTypeDefaultDescription**active**`boolean``FALSE`Whether to enable or disable the middleware ([charcoal/app](https://github.com/charcoalphp/app) only).**cache**`CacheItemPoolInterface``cache`Required; The main Stash pool.**ttl**`string[]`1 weekTime-to-live (in seconds) for a cached response.**methods**`string[]``GET`Accepted HTTP method(s) to cache the response.**status\_codes**`integer[]`200Accepted HTTP status code(s) to cache the response.**included\_path**`string[]``*`Accepted URI paths for caching the response.**excluded\_path**`string[]``^/admin\b`Rejected URI paths for caching the response.**included\_query**`string[]``NULL`Accepted query parameters for caching the response.**excluded\_query**`string[]``NULL`Rejected query parameters for caching.**ignored\_query**`string[]``NULL`Ignored query parameters for caching the response.#### By Default

[](#by-default)

All HTTP responses are cached unless:

1. the request method is not GET
2. the request URI path starts with `/admin…`
3. the request URI contains a query string
4. the response is not OK (200)

#### Ignoring Query Strings

[](#ignoring-query-strings)

If query strings don't affect the server's response, you can permit caching of requests by ignoring all query parameters:

```
"ignored_query": "*"
```

or some of them:

```
"ignored_query": [ "sort", "theme" ]
```

### Helpers

[](#helpers)

#### CachePoolAwareTrait

[](#cachepoolawaretrait)

The [`CachePoolAwareTrait`](src/Charcoal/Cache/CachePoolAwareTrait.php) is offered as a convenience to avoid duplicate / boilerplate code. It simply sets and gets an instance of `\Psr\Cache\CacheItemPoolInterface`.

Assign a cache pool with `setCachePool()` and retrieve it with `cachePool()`.

Both methods are protected; this trait has no public interface.

Resources
---------

[](#resources)

- [Contributing](https://github.com/charcoalphp/.github/blob/main/CONTRIBUTING.md)
- [Report issues](https://github.com/charcoalphp/charcoal/issues) and [send pull requests](https://github.com/charcoalphp/charcoal/pulls)in the [main Charcoal repository](https://github.com/charcoalphp/charcoal)

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community20

Small or concentrated contributor base

Maturity80

Battle-tested with a long release history

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

Recently: every ~15 days

Total

36

Last Release

788d ago

Major Versions

0.2.3 → v2.1.22022-06-21

v2.2.3 → v3.1.02022-08-08

v3.1.8 → v4.0.02022-09-21

v4.1.0 → v5.0.02024-03-13

PHP version history (2 changes)0.1.0PHP &gt;=5.6.0 || &gt;=7.0

v2.1.2PHP ^7.4 || ^8.0

### Community

Maintainers

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

![](https://www.gravatar.com/avatar/0a4f39523b4b2837562ba0848a0327b8d340118d1ba87cb0f5d59b1d5cb6beba?d=identicon)[mcaskill](/maintainers/mcaskill)

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

![](https://www.gravatar.com/avatar/4229f19eecd12c2b651b6502dcc5adfba48c5770db3d2dbea55fc92c7a246b2b?d=identicon)[BeneRoch](/maintainers/BeneRoch)

---

Top Contributors

[![mcaskill](https://avatars.githubusercontent.com/u/29353?v=4)](https://github.com/mcaskill "mcaskill (24 commits)")[![actions-user](https://avatars.githubusercontent.com/u/65916846?v=4)](https://github.com/actions-user "actions-user (16 commits)")[![JoelAlphonso](https://avatars.githubusercontent.com/u/10762266?v=4)](https://github.com/JoelAlphonso "JoelAlphonso (12 commits)")[![mducharme](https://avatars.githubusercontent.com/u/12157?v=4)](https://github.com/mducharme "mducharme (2 commits)")

---

Tags

cachecharcoalphpread-only-repositorystashcachecachingcharcoalstash

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

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

###  Alternatives

[tedivm/stash

The place to keep your cache.

9824.8M124](/packages/tedivm-stash)[tedivm/stash-bundle

Incorporates the Stash caching library into Symfony.

841.4M16](/packages/tedivm-stash-bundle)[webarchitect609/bitrix-cache

Comfortable fluent interface for Bitrix cache. Anti-stampede cache protection.

2831.2k8](/packages/webarchitect609-bitrix-cache)

PHPackages © 2026

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