Search code examples
phpcachingguzzleguzzle6

PHP: Guzzle 6 + Guzzle-cache-middleware


I've a page doing some REST queries using Guzzle 6. It works fine, however sometimes it gets too slow because it's always making queries. I found out that there is guzzle-cache-middleware that is supposed to cache responses from the remote API.

However I can't 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 don't get any errors or warnings. Guzzle still gives me the API response, however nothing new appears at /tmp/sitex.

What do I need to do in order to cache the response? Are there options like setting the TTL of the responses?

The documentation isn't very clear on how to achieve this, so if someone experienced can help me it would be nice. :)


Solution

  • 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 it's headers for cache information;
    • 180 is the TTL we want to have the cache stored.

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