A HTTP Cache for Guzzle 6. It's a simple Middleware to be added in the HandlerStack.
- RFC 7234 compliance
- Performance and transparency
- Assured compatibility with PSR-7
composer require kevinrob/guzzle-cache-middleware
or add it the your composer.json
and make a composer update kevinrob/guzzle-cache-middleware
.
Performance. It's very common to do some HTTP calls to an API for rendering a page and it takes times to do it.
With a simple Middleware added at the top of the HandlerStack
of Guzzle6.
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Kevinrob\GuzzleCache\CacheMiddleware;
// Create default HandlerStack
$stack = HandlerStack::create();
// Add this middleware to the top with `push`
$stack->push(new CacheMiddleware(), 'cache');
// Initialize the client with the handler option
$client = new Client(['handler' => $stack]);
You can use a cache from Doctrine/Cache
:
[...]
use Doctrine\Common\Cache\FilesystemCache;
use Kevinrob\GuzzleCache\Strategy\PrivateCacheStrategy;
use Kevinrob\GuzzleCache\Storage\DoctrineCacheStorage;
[...]
$stack->push(
new CacheMiddleware(
new PrivateCacheStrategy(
new DoctrineCacheStorage(
new FilesystemCache('/tmp/')
)
)
),
'cache'
);
You can use ChainCache
for using multiple CacheProvider
. With that provider, you have to sort the different cache from the faster to the slower. Like that, you can have a very fast cache.
[...]
use Doctrine\Common\Cache\ChainCache;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\Common\Cache\FilesystemCache;
use Kevinrob\GuzzleCache\Strategy\PrivateCacheStrategy;
use Kevinrob\GuzzleCache\Storage\DoctrineCacheStorage;
[...]
$stack->push(new CacheMiddleware(
new PrivateCacheStrategy(
new DoctrineCacheStorage(
new ChainCache([
new ArrayCache(),
new FilesystemCache('/tmp/'),
])
)
)
), 'cache');
It's possible to add a public shared cache to the stack:
[...]
use Doctrine\Common\Cache\FilesystemCache;
use Doctrine\Common\Cache\PredisCache;
use Kevinrob\GuzzleCache\Strategy\PrivateCacheStrategy;
use Kevinrob\GuzzleCache\Storage\DoctrineCacheStorage;
[...]
// Private caching
$stack->push(
new CacheMiddleware(
new PrivateCacheStrategy(
new DoctrineCacheStorage(
new FilesystemCache('/tmp/')
)
)
),
'private-cache'
);
// Public caching
$stack->push(
new CacheMiddleware(
new PrivateCacheStrategy(
new DoctrineCacheStorage(
new PredisCache(
new Predis\Client('tcp://10.0.0.1:6379')
)
)
)
),
'shared-cache'
);