5

I'd like to organize a .module file better by putting related hooks in other .inc files. So for example, I'd like to take a bunch of imagecache preset definitions (via hook_imagecache_default_presets) out of custom.module and put them in custom.imagecache.inc.

Where in custom.module should I include custom.imagecache.inc? I assume I'll be using module_load_include()?

If I put it in a hook_init wouldn't that include these hook definitions on every page request?

1

3 Answers 3

6

I'm pretty sure you have to put the hooks in the .module file. But what you can then do is call module_load_include() from within the hook function, and use the hook function itself as a wrapper.

So:

mymodule_hookfunction($arg) {
  module_load_include('inc', 'mymodule', 'includefile');
  return mymodule_function_that_is_in_the_include_file($arg);
}

This has the benefit of only loading the include file if the hook gets called.

NOTE: The answer really is hook_hook_info(), not this one.

1
  • Seems clean enough, I can relate to this solution.
    – ack
    Commented Jan 13, 2012 at 5:44
8

Current answer is not 100% correct for Drupal 7. In Drupal 7 there is a hook called hook_hook_info. In core this is implemented with the token module via system_hook_info. That means that for tokens the hook can be located inside of module_name.tokens.inc. So yes you can put hooks in related files by groups. Just remember that hook_hook_info must be inside of your .module file.

An example using blocks

<?php
/**
 * Implements hook_hook_info().
 */
function mymodule_hook_info() {
  $hooks['block_configure'] = array(
    'group' => 'blocks',
  );
  $hooks['block_info'] = array(
    'group' => 'blocks',
  );
  $hooks['block_info_alter'] = array(
    'group' => 'blocks',
  );
  $hooks['block_list_alter'] = array(
    'group' => 'blocks',
  );
  $hooks['block_save'] = array(
    'group' => 'blocks',
  );
  $hooks['block_view'] = array(
    'group' => 'blocks',
  );
  $hooks['block_view_alter'] = array(
    'group' => 'blocks',
  );

  return $hooks;
}
?>

You should be able to then use a mymodule.blocks.inc file to hold all your blocks information as long at the above code/hook is inside of your .module file.

3

I would just take the simplier approach and add something like:

include_once dirname(__FILE__) . '/custom.imagecache.inc';

at the beginning of my custom.module file.

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.