Guzzle Cache subscriber

49 views
Skip to first unread message

Dan Cole

unread,
Jan 19, 2015, 8:07:51 AM1/19/15
to guz...@googlegroups.com
I'm trying to set up caching with guzzle but can't seem to get it to work and haven't found any documentation on it. I'm using guzzle 5 and the description service to make calls to a web api. The cache subscriber seems to be attached to the client but no caching seems to take place on my queries when my web page is reloaded.

Here is my ClientFactory class i use to build the client :

    use Doctrine\Common\Cache\ArrayCache;
    use Doctrine\Common\Cache\FilesystemCache;
    use Guzzle\Plugin\Cache\CachePlugin;
    use GuzzleHttp\Client;
    use GuzzleHttp\Command\Guzzle\Description;
    use GuzzleHttp\Command\Guzzle\GuzzleClient;
    use GuzzleHttp\Subscriber\Cache\CacheStorage;
    use GuzzleHttp\Subscriber\Cache\CacheSubscriber;

    class ClientFactory
    {
        public static function factory(array $config = [])
        {
        $defaultConfig = [
            'defaults' => [
                'headers' => ['User-Agent' => 'MyWebApi/1.0.0 +https://mywebsite.com'],
                'auth' => 'oauth'
            ],
        ];



        $client = new Client(self::mergeRecursive($defaultConfig, $config));
        $client->setDefaultOption('verify', false);

        $array = CacheSubscriber::attach($client, [ "storage" =>  new CacheStorage(new FilesystemCache("cache/"))]);
        $service = include __DIR__ . '/../../resources/service.php';
        $description = new Description($service);

        return new GuzzleClient($client, $description);
    }

    public static function &mergeRecursive(array &$array1, &$array2 = null)
    {
        $merged = $array1;

        if (is_array($array2)) {
            foreach ($array2 as $key => $val) {
                if (is_array($array2[$key])) {
                    $merged[$key] = is_array($merged[$key]) ? self::mergeRecursive($merged[$key], $array2[$key]) : $array2[$key];
                } else {
                    $merged[$key] = $val;
                }
            }
        }

        return $merged;
    }
    }

Thanks for any answer that may help 

Reply all
Reply to author
Forward
0 new messages