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

ActiveLibrary[Caching](/categories/caching)

locomotivemtl/charcoal-cache
============================

Charcoal service provider for the Stash Cache Library

0.2.3(5y ago)010.8k4MITPHPPHP &gt;=5.6.0 || &gt;=7.0CI failing

Since May 7Pushed 3y ago11 watchersCompare

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

READMEChangelog (8)Dependencies (9)Versions (14)Used By (4)

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

[](#charcoal-cache)

[![License](https://camo.githubusercontent.com/003cb875db6cd365faa3108c9982308f7eb3a6b5688f379d2ee74bf4f54cda76/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6c6f636f6d6f746976656d746c2f63686172636f616c2d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/locomotivemtl/charcoal-cache)[![Latest Stable Version](https://camo.githubusercontent.com/ec1ffa968697b61a267ef4cd5ef8167002e195dc2e2ed259bc43406ebc93f857/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c6f636f6d6f746976656d746c2f63686172636f616c2d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/locomotivemtl/charcoal-cache)[![Code Quality](https://camo.githubusercontent.com/e43a835c95d0d0c04f10ceffd12539ea8eb850f5c0bc0d58ea4e8579fe5d6038/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6c6f636f6d6f746976656d746c2f63686172636f616c2d63616368652e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/locomotivemtl/charcoal-cache/)[![Coverage Status](https://camo.githubusercontent.com/b391cd64fe14ecd4614ba3e74d0c8b5bb2717af6e44c32abc6044fee5f014afe/68747470733a2f2f696d672e736869656c64732e696f2f636f766572616c6c732f6c6f636f6d6f746976656d746c2f63686172636f616c2d63616368652e7376673f7374796c653d666c61742d737175617265)](https://coveralls.io/r/locomotivemtl/charcoal-cache)[![SensioLabs Insight](https://camo.githubusercontent.com/0753c390fa021702ec054f2e897730a95dffb24765060895d3f39ee64ea165a1/68747470733a2f2f696d672e736869656c64732e696f2f73656e73696f6c6162732f692f2d2d2d2e7376673f7374796c653d666c61742d737175617265)](https://insight.sensiolabs.com/projects/---)[![Build Status](https://camo.githubusercontent.com/717576dcb1dbef1a00eeca2816946ccd810d83798f148a6e7cf024e24612affb/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6c6f636f6d6f746976656d746c2f63686172636f616c2d63616368652e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/locomotivemtl/charcoal-cache)

A [Charcoal](https://packagist.org/packages/locomotivemtl/charcoal-app) service provider for the [Stash Cache Library](https://packagist.org/packages/tedivm/stash).

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
    - [Dependencies](#dependencies)
    - [Dependents](#dependents)
- [Service Provider](#service-provider)
    - [Parameters](#parameters)
    - [Services](#services)
- [Configuration](#configuration)
    - [Pool Configuration](#pool-configuration)
    - [Driver Configuration](#driver-configuration)
- [Usage](#usage)
- [Middleware](#middleware)
- [Helpers](#helpers)
    - [CachePoolAwareTrait](#cachepoolawaretrait)
- [Development](#development)
    - [API Documentation](#api-documentation)
    - [Development Dependencies](#development-dependencies)
    - [Coding Style](#coding-style)
- [Credits](#credits)
- [License](#license)

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

[](#installation)

1. The preferred (and only supported) method is with Composer:

    ```
    $ composer require locomotivemtl/charcoal-cache
    ```
2. Add the service provider and configure the default caching service via the application configset:

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

    "cache": {
        "prefix": "foobar",
        "types": [ "apc", "memcache", "redis" ]
    }
    ```

    or via the service container:

    ```
    $container->register(new \Charcoal\Cache\ServiceProvider\CacheServiceProvider());

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

If you are using [*locomotivemtl/charcoal-app*](https://packagist.org/packages/locomotivemtl/charcoal-app), the [`CacheServiceProvider`](src/Charcoal/Cache/ServiceProvider/CacheServiceProvider.php) is automatically registered by the [`AppServiceProvider`](https://github.com/locomotivemtl/charcoal-app/blob/0.8.0/src/Charcoal/App/ServiceProvider/AppServiceProvider.php).

### Dependencies

[](#dependencies)

#### Required

[](#required)

- [**PHP 5.6+**](https://php.net): *PHP 7* is recommended.
- [**tedivm/stash**](https://packagist.org/packages/tedivm/stash): PSR-6 compliant caching library.
- [**pimple/pimple**](https://packagist.org/packages/pimple/pimple): PSR-11 compliant service container and provider library.
- [**locomotivemtl/charcoal-config**](https://packagist.org/packages/locomotivemtl/charcoal-config): For configuring the caching service.

#### PSR

[](#psr)

- [**PSR-3**](https://www.php-fig.org/psr/psr-3/): Common interface for logging libraries. Supported by Stash.
- [**PSR-6**](https://www.php-fig.org/psr/psr-6/): Common interface for caching libraries. Fulfilled by Stash.
- [**PSR-7**](https://www.php-fig.org/psr/psr-7/): Common interface for HTTP messages. Followed by [`CacheMiddleware`](src/Charcoal/Cache/Middleware/CacheMiddleware.php).
- [**PSR-11**](https://www.php-fig.org/psr/psr-11/): Common interface for dependency containers. Fulfilled by Pimple.

### Dependents

[](#dependents)

- [**locomotivemtl/charcoal-admin**](https://packagist.org/packages/locomotivemtl/charcoal-admin): Admin interface for Charcoal applications.
- [**locomotivemtl/charcoal-app**](https://packagist.org/packages/locomotivemtl/charcoal-app): PSR-7 compliant framework for web applications.
    For caching HTTP responses via the [`CacheMiddleware`](src/Charcoal/Cache/Middleware/CacheMiddleware.php).
- [**locomotivemtl/charcoal-core**](https://packagist.org/packages/locomotivemtl/charcoal-core): Collection, model, metadata, and database library.
    For caching object data and model metadata.

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`).### 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 [*locomotivemtl/charcoal-app*](https://packagist.org/packages/locomotivemtl/charcoal-app), you can add the middleware via the application configset:

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

Otherwise, with [Slim](https://packagist.org/packages/slim/slim), for example:

```
$app = new \Slim\App();

// Register middleware
$app->add(new \Charcoal\Cache\Middleware\CacheMiddleware([
    'cache'   => new \Stash\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 ([*locomotivemtl/charcoal-app*](https://packagist.org/packages/locomotivemtl/charcoal-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.

Development
-----------

[](#development)

To install the development environment:

```
$ composer install
```

To run the scripts (phplint, phpcs, and phpunit):

```
$ composer test
```

### API Documentation

[](#api-documentation)

- The auto-generated `phpDocumentor` API documentation is available at:

- The auto-generated `apigen` API documentation is available at:
    [https://codedoc.pub/locomotivemtl/charcoal-cache/master/](https://codedoc.pub/locomotivemtl/charcoal-cache/master/index.html)

### Development Dependencies

[](#development-dependencies)

- [php-coveralls/php-coveralls](https://packagist.org/packages/php-coveralls/php-coveralls)
- [phpunit/phpunit](https://packagist.org/packages/phpunit/phpunit)
- [squizlabs/php\_codesniffer](https://packagist.org/packages/squizlabs/php_codesniffer)

### Coding Style

[](#coding-style)

The charcoal-cache module follows the Charcoal coding-style:

- [*PSR-1*](https://www.php-fig.org/psr/psr-1/)
- [*PSR-2*](https://www.php-fig.org/psr/psr-2/)
- [*PSR-4*](https://www.php-fig.org/psr/psr-4/), autoloading is therefore provided by *Composer*.
- [*phpDocumentor*](http://phpdoc.org/) comments.
- [phpcs.xml.dist](phpcs.xml.dist) and [.editorconfig](.editorconfig) for coding standards.

> Coding style validation / enforcement can be performed with `composer phpcs`. An auto-fixer is also available with `composer phpcbf`.

Credits
-------

[](#credits)

- [Mathieu Ducharme](https://github.com/mducharme)
- [Chauncey McAskill](https://github.com/mcaskill)
- [Locomotive](https://locomotive.ca/)

License
-------

[](#license)

- Charcoal is licensed under the MIT license. See [LICENSE](LICENSE) for details.
- Stash is licensed under the BSD License. See the [LICENSE](https://github.com/tedious/Stash/blob/v0.14.2/LICENSE) file for details.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 63.2% 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 ~92 days

Recently: every ~171 days

Total

12

Last Release

1916d ago

### Community

Maintainers

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

---

Top Contributors

[![mcaskill](https://avatars.githubusercontent.com/u/29353?v=4)](https://github.com/mcaskill "mcaskill (24 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

cachecachingcharcoalstash

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/locomotivemtl-charcoal-cache/health.svg)](https://phpackages.com/packages/locomotivemtl-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)
