4

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?

1 Answer 1

8

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
3
  • 1
    I consider any module function that isn't a hook implementation and that does not begin with an underscore (_), a potential helper module.
    – mona lisa
    Commented Jan 29, 2016 at 23:27
  • @cilefen so all modules with hook functions should better start with an _?
    – nawfal
    Commented Jan 30, 2016 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. Commented Jan 30, 2016 at 7:29

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.