1

Drupal 7, custom module to output data in JSON format.

Task: create cacheable page that prints string in JSON format.

function examplemod_menu() {
  $items['json'] = [
      'page callback' => 'examplemod_json',
      'access callback' => TRUE
  ];
  return $items;
}

function examplemod_json($type='node', $id=0){
  header('Content-Type: application/json');
  print Examplemod::getResults('json', $type, $id);
  return null;
}

It works nice, page loads in ~200ms.

Then i enabled "Cache pages for anonymous users" with 1 minute "minimum cache lifetime" just for test.

Page loads in ~50ms. It looks perfect but...

Problems:

  1. My custom page not updating after 1 minute. For example, all default pages node/* and etc. are updated after 1 minute delay. Example: i visit some node page, it not loading from cache, then cache saved, and if i will refresh page again - it will load from cache. But if i will wait 1 minute or more and refresh page - it will not be loaded from cache.

So, i can't understand why my custom page every time are loaded form cache. I can wait 1 minute or more - refresh page, even multiple times - no difference - i see old version of my page loaded from cache. I didn't found any documentation about configuring menu page callback caching options. I think i'm doing something wrong.

  1. When cache for my custom page is turned off, header "Content-Type:application/json" successfully sending, but if page loading from cache - header is "Content-Type:text/html; charset=utf-8". Can it be changed for cached pages?

Yes, i can turn off cache for this page with drupal_page_is_cacheable(false), but page will load slower...

  • Regarding #1 - This is a bit confusing because you say "My custom page not updating after 1 minute" but in your example that is exactly what is happening. It is super easy to misunderstand what "minimum cache lifetime" means. Basically, by enabling this you are telling Drupal that it is OK to serve up stale content (from cache) for x amount of time (in your case 1 minute), but after that the page should be rebuilt. – othermachines Aug 6 '15 at 4:46
  • Oh, hey - here's a really great explanation of Drupal caching. Maybe it'll help: phase2technology.com/blog/caching-in-drupal – othermachines Aug 6 '15 at 4:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy