To understand the importance of caching in Drupal.
To understand the basic processes and concepts.
To have a global overview of the possible cache layers that can be found in a Drupal project.
It is a data storage layer that stores the results of operations so that when they are required again, there is no need to redo them.
Why perform an operation more than once if the result is the same?
Definition
Types (examples)
Benefits
cache.config:
class: Drupal\Core\Cache\CacheBackendInterface
tags:
- { name: cache.bin, default_backend: cache.backend.chainedfast }
factory: ['@cache_factory', 'get']
arguments: [config]
cache.entity:
class: Drupal\Core\Cache\CacheBackendInterface
tags:
- { name: cache.bin }
factory: ['@cache_factory', 'get']
arguments: [entity]
Invalidation
Variations
Cache tags
Cache contexts
Flush caches: remove cached objects directly, for example, using the command “drush cr”.
Cache invalidation: the process where cached data is invalidated because it has become outdated, with the aim of regenerating it with updated data:
Interacting directly with the Cache API of Drupal, taking care of caching objects, retrieval, and invalidation ourselves.
$cid = 'my_module_example:' . \Drupal::languageManager()
->getCurrentLanguage()->getId();
$data = NULL;
if ($cache = \Drupal::cache()->get($cid)) {
$data = $cache->data;
}
else {
$data = my_module_complicated_calculation();
\Drupal::cache()->set($cid, $data);
}
Indirectly through the Render API. This second system is the most common.
$renderer = \Drupal::service('renderer');
$config = \Drupal::config('system.site');
$current_user = \Drupal::currentUser();
$build = [
'#markup' => t('Hi, %name, welcome back to @site!', [
'%name' => $current_user->getUsername(),
'@site' => $config->get('name'),
]),
'#cache' => [
'contexts' => [
'user',
],
],
];
$renderer->addCacheableDependency($build, $config);
$user_entity = \Drupal\user\Entity\User::load($current_user->id());
$renderer->addCacheableDependency($build, $user_entity);
The dependencies defined in the different components are propagated to their ancestors for the invalidation to be effective.
Internal Page Cache
Dynamic Page Cache
It caches response objects with dynamic components by replacing those components with placeholders.
It waits until the last moment to render those components and replace the placeholders.
Buy default, Drupal stores the cache in the database.
Memcached and Redis stores cache in server memory.
Max Age (TTL). The easiest way:
Cache tags:
URLs:
purge_purger_httptc, purge_queuer_url, acquia_purge, akamai, cloudflare, cloudfront_purger, fastlypurger, keycdn, varnish_purge, max_cdn_cache, Nginx_cache_clear, purge_file
Why are response headers useful:
Standar Drupal headers:
States:
A good implementation of caching is essential in any Drupal project and involves both the development and infrastructure teams