Using The module_exists Function Effectively

Photo of Greg Harvey
Fri, 2008-12-12 13:31By greg

In our team I'm as guilty of this as anyone, but we're occasionally caught out by the creation an un-managed and un-documented dependency on a module, perhaps in a theme's template.php file or even in a module where someone forgot to list the dependency in the .info file or meant to remove the function call and forgot.

Often these things will pass through dev servers unnoticed, because different sets of modules are installed for a variety of reasons. For example, you often see people getting white screens of death because a module developer accidentally left a Devel module function call in after de-bugging. How do you deal with this? module_exists().

Consider this code:

// the module you depend on
$module = 'foo';
// the function you intend to call
$function = 'foo_do_stuff';
if (module_exists($module)) {
} else {
// module is not installed so capture the issue
watchdog('your_theme', 'Failed to call %function. The %module module is not available.', array('%function' => $function, '%module' => $module), WATCHDOG_WARNING);

Just change the watchdog parameter 'your_theme' to the name of the module or theme trying to call the function in another module and you can use this anywhere. It just means your users will never inadvertently get a white screen and you will get warned in the database log if you've done something silly! =)

Note, the watchdog() function syntax is for Drupal 6.x - can't remember if there's any difference between that and 5.x, but be mindful there could be.