In today’s tutorial, we will help you with a guide on how to get the module directory path in Magento 2?
In order to get the path, you might require the help of \Magento\Framework\Module\Dir class as shown below:\
<?php namespace MageDelight\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('MageDelight_ModuleName'); $moduleEtcPath = $this->moduleDir->getDir(MageDelight_ModuleName', Dir::MODULE_ETC_DIR); $moduleI18nPath = $this->moduleDir->getDir('MageDelight_ModuleName', Dir::MODULE_I18N_DIR); $moduleViewPath = $this->moduleDir->getDir('MageDelight_ModuleName', Dir::MODULE_VIEW_DIR); $moduleControllerPath = $this->moduleDir->getDir('MageDelight_ModuleName', Dir::MODULE_CONTROLLER_DIR); $moduleSetupPath = $this->moduleDir->getDir('MageDelight_ModuleName', Dir::MODULE_SETUP_DIR); } }
And here you go!
All you need to do is paste the above code into your controller.
This code can also be used in block, helper, and model files. We hope we have made the process easier for you, still if you face any issue, feel free to reach us out!
Also read: How to Modify the Magento 2 Root Directory?