sobi3ch
sobi3ch

Reputation: 2833

How can I get Drupal module name programmatically?

I'm working on my own module. I realize I constantly need to manually type my module name in different places. Most popular usage is with drupal_get_path($type, $name) function (I have more then 10 of these in my code). Where $name is theme or module name. During that time I need to already change my module name 3 times. As you can surmise I also need change all module names hard-coded in my project. So I thought it would be nice to have some convenient function to grab this name automatically.

How can I get machine module name programmatically?

For example if you have your module in following directory..

sites/all/modules/my_module/

..then you can grab it in this way

drupal_get_current_module_name(); // return my_module

Upvotes: 1

Views: 3415

Answers (2)

sobi3ch
sobi3ch

Reputation: 2833

I figure out something like this:

function get_current_module_name() {
    return array_shift(explode('.', end(explode(DIRECTORY_SEPARATOR, __FILE__))));
}

but don't know is't the best way to do it..

UPDATE: I see now it's better to use basename

$name = basename(__FILE__, '.module');

UPDATE 2: I think if this is needed across whole module then it could be accessible via constant defined in the very beginning of the module e.g.:

define('MODULE_NAME', basename(__FILE__, '.module'));

Then you could use all the time in all your function like this:

drupal_get_path('module', MODULE_NAME);

Upvotes: 1

jmdodge
jmdodge

Reputation: 31

Generally, you should know by convention - if you have: sites/all/modules/my_module/ then the machine name of the module should match the folder name - my_module.

Virtually all contributed modules follow this convention, and you should too.

It is possible to have your .info and .module file not match the name of the folder, but this isn't correct.

If you are already executing code inside your module, you should already know the machine name of the module by virtue of the name of the file you're editing - unless you're trying to do something that I'm not understanding.

Edit: Since we've determined you're just trying to call your module's theme function, you don't actually need to know the name.

If you have:

/** Implements theme_table **/
function my_really_long_module_name_table() {}

Your function might get called like this:

theme('table');

There is a little more to it than that, but the theme engine will make a determination about which theme functions get called based on what is implementing them.

It sounds like you may want to read up on some of the basics of the Drupal theme system. Here's a good start for learning the Drupal 6 theme layer: http://drupal.org/node/165706

Upvotes: 2

Related Questions