1

In my module I have the following:

$client = new Client(['base_uri' => myBaseUri]);

$response = $client->request('GET', myQueryString, [
    'headers' => [
        'Accept'            => 'application/json',
        'Accept-Encoding'   => 'deflate,gzip'
    ],
    'connect_timeout' => 3,
    'verify' => false,
    'timeout' => 5,
    'http_errors' => false
]);

$json = $response->getBody();
$data = json_decode($json, true);

How can I cache this so it only does the request every 5 minutes?

3

You can either cache it globally or in the session

// your cache key
$key = 'akey';

$cache = Craft::$app->getCache();
$value = $cache->get($key);
// check if there is a valid value that is not older than 5 minutes
if ($value !== null && \is_array($value) && isset($value['time']) &&
    $value['time'] >= time() - 3600) {
    return $value['value'];
}

// make your request
$response = Craft::createGuzzleClient(['base_uri' => $myBaseUri])
    ->get('GET', myQueryString, [
    'headers' => [
        'Accept'            => 'application/json',
        'Accept-Encoding'   => 'deflate,gzip'
    ],
    'connect_timeout' => 3,
    'verify' => false,
    'timeout' => 5,
    'http_errors' => false
]);

$json = $response->getBody();
$data = Json::decode($json, true);

// cache it
$cache->set($key,  
    'time'  => time(),
    'value' => $data
]);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.