0

When you have a larger project you probably have both internal page cache as internal dynamic page cache module enabled. In my case I do. But I have a section on my website containing custom entities ('Contest') where I would like to have custom-tailored control of caching of the detail page (contest/1). This is what I found so far:

/**
 * Implements hook_entity_view_alter()
 * Disable caching on all contest entity types
 */
function mymodule_entity_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  $types = ['contest'];
  if (in_array($entity->bundle(), $types)) {
    $build['#cache']['max-age'] = 0;
    \Drupal::service('page_cache_kill_switch')->trigger();
  }
}

Is this the only way? I'd expect to have a more clean way, in my Contest.php perhaps? Looking forward to possible answers!

4
  • It's unclear what you are asking. The Dynamic Page Cache respects max-age = 0, so there is no more clean way to disable it. Do you mean the Internal Page Cache? Only if you've enabled this module you would need the additional kill switch. Or do you mean the response headers to control the browser cache?
    – 4uk4
    Oct 18, 2021 at 13:33
  • Thanks for replying. Sorry, I mean both internal page cache as Internal Dynamic Page Cache. Let's consider both modules to be enabled. I was just wondering if there is a more OO way to define the caching of the custom entity detail pages. Oct 18, 2021 at 14:06
  • There are more things unclear. Your code is checking for a bundle, but it seems like you want to check getEntityTypeId(). If this is the case you could add the option no_cache: TRUE to the entity routes (route_provider in your entity class Contest).
    – 4uk4
    Oct 18, 2021 at 14:12
  • Correct answer below was exactly what I was looking for. Thanks. Oct 19, 2021 at 6:56

1 Answer 1

2

I was just wondering if there is a more OO way to define the caching of the custom entity detail pages.

This would be extending the route provider you are using now (DefaultHtmlRouteProvider or AdminHtmlRouteProvider), specifying it in the custom entity class

*     "route_provider" = {
*       "html" = "Drupal\mymodule\MyEntityRouteProvider",
*     },

and overriding getCanonicalRoute to add the no_cache option:

protected function getCanonicalRoute(EntityTypeInterface $entity_type) {
  $route = parent::getCanonicalRoute($entity_type);
  $route->setOption('no_cache', TRUE);
  return $route;
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.