Optimize to do:
expire
/ varnish
module in D7.The theory of how we make Drupal fast
drupal_add_css()
, drupal_add_js()
…
#attached
asset libraries solve thaturl()
's output depended on:
<front>
configuration
+
Cacheability bubbled during rendering!
Try to make this thought process a habit:
I'm rendering something. That means I must think of cacheability!
Is this something that's expensive to render, and therefore is worth caching?
↪︎ If "yes": cache keys
$build['#cache']['keys'] = ['node', 5, 'teaser'];
Does the representation of the thing I'm rendering vary per combination of permissions, per URL, per interface language, per … something?
↪︎ If "yes": cache contexts
$build['#cache']['contexts'][] = 'user.permissions';
$build['#cache']['contexts'][] = 'url';
~ HTTP's Vary
header
What causes the representation of the thing I'm rendering become outdated?
↪︎ If "yes": cache tags
$build['#cache']['tags'][] = 'node:5';
$build['#cache']['tags'][] = 'user:3';
$build['#cache']['tags'][] = 'taxonomy_term:23';
When does the representation of the thing I'm rendering become outdated?↪︎ If "yes": cache max-age
$build['#cache']['max-age'] = Cache::PERMANENT;
~ HTTP's Cache-Control: max-age
header
To make it easier:
Renderer::addCacheableDependency($dependency)
$site_config = $this->config->get('system.site');
$build = [
'#markup' => t('Welcome to @site!', $site_config->get('name')),
];
$this->renderer->addCacheableDependency($site_config)
(Drupal rendering a page ~ building a ship)
Don't forget to add its cache tags!
Renderer::addCacheableDependency($build, $config)
Don't forget to add its cache tags!
Renderer::addCacheableDependency($build, $entity)
Don't forget to add the entity's cache tags!
Renderer::addCacheableDependency($build, $entity)
Don't forget to set max-age to zero!
$build['#cache']['max-age'] = 0;
Either:
{{ link(something.title, something.url) }}
#type => link
:
$build['link'] = [
'#type' => 'link',
'#title' => 'Drupal',
'#url' => Url::fromUri('https://drupal.org'),
];
$args = ['%username' => $_COOKIE['username']];
$build['#markup'] = $this->t('Hi, %username', $args);
$build['#cache']['contexts'][] = 'cookies:username';
In sites/yoursite.com/services.yml
:
parameters:
renderer.config:
required_cache_contexts:
# The two default required cache contexts.
- 'languages:language_interface'
- 'theme'
# The one we added!
- 'cookies:device'
wimleers.com/talk/making-drupal-fly-fastest-drupal-ever-near
d.o/developing/api/8/cache/contexts
d.o/developing/api/8/render/arrays/cacheability