At times you have to write little utility functions which will have a general scope (not restricted to the module you are working on) so that it can be called from anywhere in the project.

I know I can write it anywhere and include the php file from the caller, but is there a convention followed in Drupal?

For e.g. I am working on xyz.module which does xyz thing which will have a silly

function startsWith($haystack, $needle) // case-insensitive startsWith
    return strncasecmp($haystack, $needle, strlen($needle)) === 0;

Where shall I write that function?


As many API modules do, you can place your global helper functions within a dedicated module. (I'll be using MYHELPERMODULE in the following example.)

You then should follow the naming conventions:

function MYHELPERMODULE_startswith($needle, $haystack) {
  // do your magic

You can call this function from within all other modules, as long as your helper module is active. To assure it's active, add your helper module as dependency to the .info file of the module that is using the helper function:

dependencies[] = MYHELPERMODULE
  • 1
    I consider any module function that isn't a hook implementation and that does not begin with an underscore (_), a potential helper module. – cilefen Jan 29 '16 at 23:27
  • @cilefen so all modules with hook functions should better start with an _? – nawfal Jan 30 '16 at 6:42
  • He is speaking of function names only. Mentioning, that function names starting with an underscore are considered private for the containing module. Hooks are a completely different topic. – Mario Steinitz Jan 30 '16 at 7:29

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.