When you want to store hard to compute data in memory you use a static variable. But to store this data in the database the State API is not the right place, despite the similar name:
The State API provides a place for developers to store information about the system's state.
A system state is for example the last time cron has run. So the State API \Drupal::state
has nothing to do with caching at all.
Use insteadthe Cache API Drupal::cache()
instead.
StoreExample how to store data in cache:
\Drupal::cache('data')->set($cid, $data, Cache::PERMANENT, ['heavy:' . $heavy_id]);
$cid
is a unique cache key, which is used to retrieve the data from cache:
$data = \Drupal::cache('data')->get($cid);
Set aYou can use the cache tag you've set above as fourth parameter so that you canto invalidate the cache entry if it becomes outdated:
\Drupal\Core\Cache\Cache::invalidateTags(['heavy:1']);