Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the current module name

Is there a way to get the name of the module you are working within? I have a large set of modules (about 35) with some common functionality. Long story short is that I would like to be able to get the module name without hard-coding it in a string. Hopefully this isn't necessary, but here's an idea of what I'm trying for:

function MYMODULE_mycustom_hook($args) {
    $sCurrModule = 'MYMODULE';

    // Operations using $sCurrModule...
}

Essentially, I can replace 'MYMODULE' with the module name and be done with it, but I'm wondering if there is a way to get that value programmatically. I'm using Drupal 7.

This does not apply to Drupal 8.

like image 549
Lawrence Johnson Avatar asked May 20 '13 20:05

Lawrence Johnson


2 Answers

If your module file is sites/default/modules/MYMODULE/MYMODULE.module then module name is MYMODULE.

You can get it programmatically inside MYMODULE.module file using following command:

$module_name = basename(__FILE__, '.module');
like image 159
Sumoanand Avatar answered Oct 13 '22 01:10

Sumoanand


Although OP was asking regarding D7, here's the solution for Drupal 8 (D8) as well:

/** @var \Drupal\Core\Extension\ModuleHandlerInterface $module_handler */
$module_handler = \Drupal::service('module_handler');

/** @var \Drupal\Core\Extension\Extension $module_object */
$module_object = $module_handler->getModule(basename(__FILE__, '.module'));

$module_name = $module_object->getName();

Of course, you can chain these calls if necessary:

\Drupal::service('module_handler')->getModule(basename(__FILE__, '.module'))->getName()
like image 21
Balu Ertl Avatar answered Oct 13 '22 01:10

Balu Ertl