3

In Magento 1, the static getModuleDir method of the Mage class

Mage::getModuleDir('', 'Mage_Core') 

provided a stable, "works across versions" way of getting the base folder of a Magento module.

Does Magento 2 have something similar? I found the Magento\Framework\Module\Dir\Reader class that has a getModuleDir method.

#File: vendor/magento/framework/Module/Dir/Reader.php
/**
 * Get module directory by directory type
 *
 * @param string $type
 * @param string $moduleName
 * @return string
 */
public function getModuleDir($type, $moduleName)
{
    if (isset($this->customModuleDirs[$moduleName][$type])) {
        return $this->customModuleDirs[$moduleName][$type];
    }
    return $this->moduleDirs->getDir($moduleName, $type);
}

I could inject this class as a dependency in my own class and call this method. However, this method is not marked with any sort of @api flag, which means it might change unexpectedly.

Is there a safe/stable way for extension developers to determine which folder their module is in (in order to load extra configuration or data files that ship with the module)? Or do we need to roll the dice the the above class, and/or do directory traversing tricks with __FILE__ and __DIR__?

4
  • Since getModuleDir is a public function it is probably somewhat safe, since developers can use it in plugins and Magento will (hopefully!) be hesitant to remove or alter it.
    – user50408
    Commented Feb 23, 2017 at 0:54
  • 1
    @dmatthew Based on experience, your hope is somewhat misplaced. Commented Feb 23, 2017 at 0:57
  • @dmatthew what happens when someone deploys my code to their system and updates to a version of Magento that changes this? Commented Feb 23, 2017 at 1:10
  • The Magento\Framework\Component\ComponentRegistrar::getPath function looks to fit your needs.
    – user50408
    Commented Feb 23, 2017 at 1:12

1 Answer 1

6

You can use the ComponentRegistrar by injecting ComponentRegistrarInterface and get a module's directory like this:

$path = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, 'Your_Module');

Since all modules are required to register their directory with this class in their registration.php file, it doesn't seem like something magento would change.

1
  • 2
    +1 I like it -- although since the only method that all modules call is public static function register that's the only one I'd trust to stick around. A good alternative when nothing official comes through :) Commented Feb 23, 2017 at 2:04

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.