0

I am trying to learn more about modules and have noticed several of the ones I've been investigating contain .inc files, eg: module_name.inc or module_name.theme.inc.

It's clear these contain hooks and functions and are probably separated out just for organisational purposes.

But how does the module/Drupal know these exist? How are they called upon? I see no reference to these files in the module_name.module file. Does Drupal automatically include all .inc files within the module's directory?

1 Answer 1

2

There are multiple ways .inc files can be included.

Hooks in general should all be included in the .module file, as that is the only file loaded on every page load by default, and hooks should always be available. However, hook_hook_info() can be implemented, telling Drupal that the hook should be looked for in another file. For example:

function hook_hook_info()
{
  return array
  (
    // Tell Drupal to look in a different file
    // for hook_form_alter:
    'form_alter' => array
    (
      // Tell Drupal to look in MODULENAME.forms.inc
      // for hook_form_alter:
      'group' => 'forms',
    ),
  ),
}

Next, you can use hook_menu() to look for a callback in an .inc file:

function hook_menu()
{
  $menu['some/path'] = array
  (
    ...
    'file' => 'includes/some_file.inc',
  );

  return $menu;
}

The same can be done with hook_theme():

function hook_theme()
{
  $themes['some_theme_hook'] = array
  (
    ...
    'file' => 'includes/some_file.inc',
  );

  return $themes;
}

.inc files can also be directly included with module_load_include():

// The extension is given in the first argument, and
// left off the last argument:
module_load_include('inc', MODULENAME, 'includes/some_file');

Though in forms, form_load_include() should be used rather than module_load_include():

// The extension is given in the second argument, and
// left off the last argument:
form_load_include($form_state,'inc', MODULENAME, 'includes/some_file');
2
  • Somewhat disagree with second paragraph. Not loading a file lowers the memory footprint for a page. So, if a page can't result in that hook being called, then there is no need for it in the request. Same for theme and page callbacks. This can add up.
    – mpdonadio
    Mar 24, 2017 at 2:00
  • I'm sorry, I can't really understand what you are trying to say there.
    – Jaypan
    Mar 24, 2017 at 2:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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