I notice that many core modules in Drupal 7 implement hook_token_info
and hook_tokens
in a hook.tokens.inc
file, but I can't figure out how this file is included. Should I be doing the same with my own module? How can I be sure it will be loaded?
1 Answer
They do it by way of hook_hook_info()
:
Defines one or more hooks that are exposed by a module.
Normally hooks do not need to be explicitly defined. However, by declaring a hook explicitly, a module may define a "group" for it. Modules that implement a hook may then place their implementation in either $module.module or in $module.$group.inc. If the hook is located in $module.$group.inc, then that file will be automatically loaded when needed. In general, hooks that are rarely invoked and/or are very large should be placed in a separate include file, while hooks that are very short or very frequently called should be left in the main module file so that they are always available.
As luck would have it, the example from the docs shows exactly how the Token module does it:
function hook_hook_info() {
$hooks['token_info'] = array(
'group' => 'tokens',
);
$hooks['tokens'] = array(
'group' => 'tokens',
);
return $hooks;
}
Should I be doing the same with my own module?
Totally up to you - it certainly can't hurt, other modules that need to implement your hook will just have an extra option for storing the hooks. But if you don't, they can still implement your hooks in the .module file anyway.
-
By "should I be doing the same", I meant should I put tokens in a separate file like that?– meustrusCommented May 22, 2014 at 19:35
-
Ah ok - same response really, totally up to you :) This sort of thing will come in more useful as your module grows and you start implementing a lot of hooks. By then you'll probably want to trim the main .module file down, and the reason this hook exists will be very clear– Clive ♦Commented May 22, 2014 at 20:07
-
Well, between eight hook implementations, one API function, and four "private" helper functions, totaling more than 500 lines, shaving off the token components (which are the largest implementations) does make it a bit easier to manage. Now that I know how that $module.tokens.inc file gets loaded I can take advantage of it. I was not aware of hook_hook_info; thanks for the answer!– meustrusCommented May 22, 2014 at 20:22