2

I wrote my first module which happens to be in Drupal 7. The module uses hook_menu to correlate URLs with three custom-coded, page call backs. These callback functions that construct the custom html are currently inside the .module file.

The file is getting a little long and I would like to put the three custom-coded page call backs into another file. My first attempt did not work this morning, I'm not sure what I did wrong...

1) Added this line to the .info file:

files[] = my_module.pages.inc

2) Placed the callbacks into my_module.pages.inc

What is wrong or missing in this approach?

  • 2
    files[] is for autoloading classes, not for including files. – Clive Feb 6 '13 at 14:58
  • 1
    The files attribute in the modules' info files have a different purpose. Simply put, it gives you an autoloader mechanism, so that when you implement a class in your module the specified files will be sought by the system in order to instantiate the class when it's needed. – balintk Feb 6 '13 at 15:03
6

You can enter a file parameter in the hook_menu function and the file will be included before calling the page callback function.

<?php
function my_module_menu() {
  $items = array();
  $items['my/custom/path'] = array(
    'title' => 'My title',
    'page callback' => 'my_function',
    ...
    'file' => 'my_module.pages.inc',
  );
  return $items;
}

Now, you can place your my_function in the my_module.pages.inc file. You can place submit and validate handlers (forms) in this page as well.

files[] = my_module.pages.inc

will not work. It's to autoload classes. A good example would be Views file includes.

  • You are part of the awesomeness that is stack exchange. Thanks! – user1706487 Feb 6 '13 at 15:08
4

hook_menu() already provides a method to put page callbacks in other files. Take a look at the file parameter

A file that will be included before the page callback is called; this allows page callback functions to be in separate files. The file should be relative to the implementing module's directory unless otherwise specified by the "file path" option. Does not apply to other callbacks (only page callback).

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.