drupal Cache - ben600324/wiki GitHub Wiki
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
function mymodule_get_data_from_query($params) {
$cache_key = 'mymodule_query_results:' . sha1(serialize($params));
$cache_tags = ['mymodule_query_results'];
// Check if the data is already cached.
$cache = \Drupal::cache();
$cache_data = $cache->get($cache_key);
if ($cache_data) {
$data = $cache_data->data;
}
else {
// Execute the query to retrieve the data.
$query = \Drupal::database()->getQuery();
// Build your query using the $query object and $params.
// ...
`$data = $query->execute();`
`// Store the data in cache with a specific expiration time.`
`$expiration = Cache::PERMANENT;`
`$cache_duration = 3600; // Cache duration of 1 hour.`
`$cache->set($cache_key, $data, time() + $cache_duration, $cache_tags);`
}
return $data;
}