2

Here's a simple "Hello World" controller. It's working correctly, except for the "max-age" statement. The request returns a Drupal cache hit every time after the first request, rather than just for 5 seconds. I've tried to find a simple example of how to do this but haven't had much luck. If anyone could help, that would be very much appreciated.

<?php
/**
 * @file
 * Contains \Drupal\hello_world\Controller\HelloController.
 */

namespace Drupal\hello_world\Controller;
use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {

  public function content() {

    return array(
      '#type' => 'markup',
      '#markup' => $this->t('Hello, World!'),

      // THIS ISN'T WORKING:
      '#cache' => array("max-age" => 5),
    );
  }
}
?>
2
  • Are you sure you're not exceeding 5 seconds in the time it takes you to make the additional request? What happens when you use a value such as 60?
    – mradcliffe
    Commented Feb 15, 2016 at 16:30
  • As it's a very fast "hello world" page, it's not exceeding 5 seconds. I'm getting cache HITS (page IS being cached), both before and after 5 seconds.
    – rangfu
    Commented Feb 15, 2016 at 19:35

1 Answer 1

4

The page cache module doesn't respect max-age. Unfortunate but the problem is that Drupal usually contains elements like forms that are by default set to max-age 0, but that only applies to authenticated users most of the time.

To invalidate the page cache, you need to use cache tags, which you invalidate when something changes.

If that doesn't work, you can try to set the Expires header on the response, but for that you either need to return a Response object or alter it in an event when it has been created.

Note: max-age does work for dynamic page cache (authenticated users), rendered blocks, views, entities and so on. Just not for the anonymous page cache.

3
  • thank you very much for the info, that is really useful.
    – rangfu
    Commented Feb 15, 2016 at 19:31
  • Can you give a code example of using the cache tags? And when using cache tags, should you NOT use '#cache' => array("max-age" => x) ? Commented May 18, 2016 at 20:49
  • drupal.org/developing/api/8/render/arrays/cacheability has examples, see also the Cache tags link at the end. You can mix contexts, tags and max-age in any way you see fit.
    – Berdir
    Commented May 18, 2016 at 21:39

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.