I am trying to cache manually a response from an external api that I call from a controller function.
So I used informations from https://api.drupal.org/api/drupal/core!core.api.php/group/cache/8.2.x
I use \Drupal::cache()->set($cid, $data, 300) to store the data and I can see the line on the DB (cache_default table) with the right cid, but every time I call \Drupal::cache()->get($cid) it returns FALSE as if the cache did not exist or was invalid.
For the moment my solution is to query the database (cache_default) table, get the created date and expire and data as well, compare with current time, and if current time is inferior to expire time, set my array with the cached data.
$query = \Drupal::database()->select('cache_default', 'cd')
->fields('cd')
->condition('cd.cid', $cid, 'LIKE');
$cachedResults = $query->execute()->fetchAll();
$cachedResult = reset($cachedResults);
$created = (int) round($cachedResult->created);
$expire = $cachedResult->expire;
$t = time();
// Cache is still valid.
if (($created + $expire) > $t) {
$data = unserialize($cachedResult->data);
}
// Cache is no more valid.
else {
// Call to the API and set data by myself.
...
\Drupal::cache()->set($cid, $data, 300);
}
But I am not obviously happy to take such unofficial way to generate my cache.
Could you help me to understand what I do wrong ?
Comments
Comment #2
m.krestnicov CreditAttribution: m.krestnicov as a volunteer commentedTry this:
\Drupal::cache()->set($cid, $data, time() + 300);
Comment #3
BerdirExactly, the time is not an age, it is an expiration time, so you always need to add the current time. This is different from max-age used in render-caching.