I have declared two items in my hook menu.

//Calls a function that enables inputting/updating data of a particular template.
$items['user/%user/myid_inputting'] = array(
    'title' => 'MyID Inputting',
    'description' => 'Inputting data for a particular data',
    'page callback' => 'myid_inputting',   
    'page arguments' => array(1),   
    'access arguments' => array('perform_regular_task'),
    'file' => 'includes/myid_inputting.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -20,

//Calls a function that enables ID printing
$items['user/%user/myid_printing'] = array(
    'title' => 'MyID Printing',
    'page callback' => 'myid_printing',
    'page arguments' => array(1),    
    'access arguments' => array('perform_regular_task'),   
    'file' => 'includes/myid_printing.inc',    
    'type' => MENU_LOCAL_TASK,
    'weight' => -19,

I had used two separate files for the two items. Is that best practice in Drupal? I just notice some functions that I used are redundant when separating the code between the two. What are advantages and disadvantages of doing so?

  • 2
    Which functions are redundant when separating the code in two files? The general rule is to group functions by domain. For example, functions related to admin in yourmodule.admin.inc or related to forms in yourmodule.forms.inc BUT this a hint not a enforced rule. IMHO I think is good to separate even in more files as you want to do. – sanzante Mar 1 '16 at 8:42

If the code in myid_inputting() and myid_printing() is different and large, you might want to keep these callbacks separate. I generally avoid having too many lines in one file, so whenever it's possible to logically organize the code of your module into files, it's better to do so.

Regarding the code that is redundant: I always have a separate file with helper functions where I store functions that need to be shared. Include this file at the top of the .module file, and you're all set. You can see an example in my D7 module boilerplate on Github.

Here's how you would include the helpers file (this would go at the top of the .module file):

// Load the helper functions.
require_once dirname(__FILE__) . '/YOUR_MODULE.helpers.inc';

Back to your case - leave different code in separate files, make helper functions for the rest and move it to YOUR_MODULE.helpers.inc. This works great for very large modules as well, and is self explanatory when more people are working with you on a project.

Hope this helps.

  • You're welcome, glad it helped. – Aram Boyajyan Mar 1 '16 at 9:03

Your Answer

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