You are here

protected function View::addCacheMetadata in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/views/src/Entity/View.php \Drupal\views\Entity\View::addCacheMetadata()

Fills in the cache metadata of this view.

Cache metadata is set per view and per display, and ends up being stored in the view's configuration. This allows Views to determine very efficiently:

  • the max-age
  • the cache contexts
  • the cache tags

In other words: this allows us to do the (expensive) work of initializing Views plugins and handlers to determine their effect on the cacheability of a view at save time rather than at runtime.

1 call to View::addCacheMetadata()
View::preSave in core/modules/views/src/Entity/View.php
Acts on an entity before the presave hook is invoked.

File

core/modules/views/src/Entity/View.php, line 322
Contains \Drupal\views\Entity\View.

Class

View
Defines a View configuration entity class.

Namespace

Drupal\views\Entity

Code

protected function addCacheMetadata() {
  $executable = $this
    ->getExecutable();
  $current_display = $executable->current_display;
  $displays = $this
    ->get('display');
  foreach (array_keys($displays) as $display_id) {
    $display =& $this
      ->getDisplay($display_id);
    $executable
      ->setDisplay($display_id);
    $cache_metadata = $executable
      ->getDisplay()
      ->calculateCacheMetadata();
    $display['cache_metadata']['max-age'] = $cache_metadata
      ->getCacheMaxAge();
    $display['cache_metadata']['contexts'] = $cache_metadata
      ->getCacheContexts();
    $display['cache_metadata']['tags'] = $cache_metadata
      ->getCacheTags();

    // Always include at least the 'languages:' context as there will most
    // probably be translatable strings in the view output.
    $display['cache_metadata']['contexts'] = Cache::mergeContexts($display['cache_metadata']['contexts'], [
      'languages:' . LanguageInterface::TYPE_INTERFACE,
    ]);
  }

  // Restore the previous active display.
  $executable
    ->setDisplay($current_display);
}