0

For example, I'd like node_load to load the path alias of the node, and cache it for future node_load calls (just like node_load caches all of the data, i think). I assume this is done in a module, but I haven't been able to find examples of this.

0

The hook you're after is called hook_node_load(). I think the example from that page is probably the easiest to understand:

function hook_node_load($nodes, $types) {
  $result = db_query('SELECT nid, foo FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)));
  foreach ($result as $record) {
    $nodes[$record->nid]->foo = $record->foo;
  }
}

The example loads some custom data from a table, based on the ids of the nodes passed into the function. It then loops through the query results, and adds the custom data to the relevant node objects.

When you call node_load() or node_load_multiple() for nodes that haven't been cached yet, your hook_node_load() function will be called and the custom data added.

Next time you call those functions for the same nodes your hook won't be called, but the node objects returned from the static cache will already have your custom data attached to them.

3
  • Are you sure about this? I've read elsewhere that hook_node_load will NOT cache your custom data, i.e. drupal.stackexchange.com/questions/25928/…
    – maxedison
    May 20 '12 at 13:01
  • I'm talking about the static page cache, not the persistent database cache. If you want to cache the results of your database call then yes, you'll need to do that yourself. But that's true of absolutely any situation where you use data from a custom database in Drupal. The example in Chapabu's answer from that question is great, if you combine that logic with the above then you'll have persistent and static page caching for your data. Sorry for the misunderstanding
    – Clive
    May 20 '12 at 13:45
  • I see, my mistake entirely. Thanks for the clarification. Static page cache is actually what I'm after, so this is perfect.
    – maxedison
    May 20 '12 at 13:50

Your Answer

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

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