Middleware with various cache utilities

v1.1.0 2018-08-04 10:41 UTC


Latest Version on Packagist Software License Build Status Quality Score Total Downloads SensioLabs Insight

Middleware components with the following cache utilities:



This package is installable and autoloadable via Composer as middlewares/cache.

composer require middlewares/cache


To add the response headers for cache prevention. Useful in development environments:

$dispatcher = new Dispatcher([
    new Middlewares\CachePrevention()

$response = $dispatcher->dispatch(new ServerRequest());


To add the Expires and Cache-Control: max-age headers to the response.

__construct(array $expires = null)

Set the available expires for each mimetype. If it's not defined, use the defaults.

defaultExpires(string $expires)

Set the default expires value if the request mimetype does not match. By default is 1 month. Example:

$dispatcher = new Dispatcher([
    (new Middlewares\Expires([ //set 1 year lifetime to css and js
        'text/css' => '+1 year',
        'text/javascript' => '+1 year',
    ]))->defaultExpires('+1 hour') //and 1 hour to everything else

$response = $dispatcher->dispatch(new ServerRequest());


Saves the response headers in a PSR-6 cache pool and returns 304 responses (Not modified) if the response is still valid. This saves server resources and bandwidth because the body is returned empty. It's recomended to combine it with Expires to set the lifetime of the responses.

__construct(Psr\Cache\CacheItemPoolInterface $cache)

The cache pool instance used to save the responses headers.

$dispatcher = new Dispatcher([
    new Middlewares\Cache($cache),
    new Middlewares\Expires()

$response = $dispatcher->dispatch(new ServerRequest());

responseFactory(Psr\Http\Message\ResponseFactoryInterface $responseFactory)

A PSR-17 factory to create the 304 responses.

Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.

The MIT License (MIT). Please see LICENSE for more information.