PHP: Guzzle 6 + Guzzle-cache-middleware

I have a page that performs some REST requests using Guzzle 6. It works fine, however sometimes it slows down because it always makes requests. I found out that there is guzzle-cache-middleware that should cache remote API responses.

However, I cannot get it to work, my code follows something like:

use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use League\Flysystem\Adapter\Local; use Kevinrob\GuzzleCache\CacheMiddleware; use Kevinrob\GuzzleCache\Strategy\PrivateCacheStrategy; use Kevinrob\GuzzleCache\Storage\FlysystemStorage; (...) $stack = HandlerStack::create(); $stack->push( new CacheMiddleware( new PrivateCacheStrategy( new FlysystemStorage( new Local("/tmp/sitex") ) ) ), "cache" ); // Request $client = new Client([ "handler" => $stack, "base_uri" => "http://..., "timeout" => 2.0, ]); $response = $client->request("GET", "/posts", [ (...) 

After running the code, I get no errors or warnings. Guzzle still gives me an API response, however nothing appears in /tmp/sitex .

Do I need to install anything after the request to cache the response? Are there options such as setting TTL responses?

The documentation does not explain any of this, so if someone who tested on Guzla can help me, it would be nice. :)

+5
source share
1 answer

I managed to fix this by replacing $stack->push( with:

 $stack->push( new CacheMiddleware( new GreedyCacheStrategy( new FlysystemStorage( new Local("/tmp/sitex") ), 180 ) ), "cache" ); 
  • GreedyCacheStrategy: always cache the response without checking its headers for cache information;
  • 180 is the TTL we want to cache.

Also replace use Kevinrob\GuzzleCache\Strategy\PrivateCacheStrategy; at use Kevinrob\GuzzleCache\Strategy\GreedyCacheStrategy;

+5
source

All Articles