How to Get Module Directory Path in Magento 2
Hello Readers! In this blog I will show you how can you get the path of any installed modules. Also the path of some folders related to the module such as etc, controller folders.
To get the paths you need take help of \Magento\Framework\Module\Dir class as shown below,
<?php
namespace Webkul\ModuleName\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Module\Dir;
class Blog extends Action
{
public function __construct(
Context $context,
Dir $moduleDir
) {
$this->moduleDir = $moduleDir;
parent::__construct($context);
}
public function execute()
{
$modulePath = $this->moduleDir->getDir('Webkul_ModuleName');
$moduleEtcPath = $this->moduleDir->getDir('Webkul_ModuleName', Dir::MODULE_ETC_DIR);
$moduleI18nPath = $this->moduleDir->getDir('Webkul_ModuleName', Dir::MODULE_I18N_DIR);
$moduleViewPath = $this->moduleDir->getDir('Webkul_ModuleName', Dir::MODULE_VIEW_DIR);
$moduleControllerPath = $this->moduleDir->getDir('Webkul_ModuleName', Dir::MODULE_CONTROLLER_DIR);
$moduleSetupPath = $this->moduleDir->getDir('Webkul_ModuleName', Dir::MODULE_SETUP_DIR);
}
}
If we do not provide any second parameter then getDir method will return path to module’s directory. We can provide the second parameter to get the specific folders of a module.
Thanks for reading the blog. Feel free to comment if you face any issue.
Categories:
Magento 2
View Comments (1)
Comment or Ask a Question
Quick Links