Tag: cache

I'm working on a Drupal project that requires calculating some custom stats for each registered user. To get it working, I ran my SQL queries right in hook_user_load(), which is wildly inefficient; it's much better to run the queries once and cache the results for a while. Drupal has nice cache functions built-in, and I thought I should use them, but wasn't totally clear on how to do it based on the documentation.

Jeff Eaton of Lullabot wrote a really helpful article on how to do basic caching in Drupal 7, which is a good introduction, but didn't really explain how to cache a bunch of related, but separately calculated, pieces of data using a function you'd call repeatedly. Examples module is also great, and does include a cache_example module, but also didn't have an example that was right up my alley.

So, here's how to write a single function that can be called multiple times on the same kind of object. This is not what you'd want to do for users or other built-in entities (for those, you should use Entity Cache module). Thanks to Planet Drupal readers for the feedback and help clarifying this.