Magento, Magento 2

How to Get Module Directory Path in Magento 2

How to Get Module Directory Path in Magento 2

In this tutorial, Today I will explain to how to get module directory path in Magento 2. To get the paths you need take help of \Magento\Framework\Module\Dir class. Whenever, you will need to get folder structure path in your code logic at that time, this will useful for get directory file path. Let’s see the below steps :

You may also like this :

Steps to Get Module Directory Path in Magento 2 :

1) First of all, Let’s assume that you have created sample module. Now, paste the below code in your controller :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Controller\Index;

use Magento\Framework\App\Action\Action;

class Index extends Action
{
    /**
     * @var \Magento\Framework\Module\Dir\Reader
     */
    protected $moduleDirectory;

    /**
     * @param  \Magento\Framework\App\Action\Context $context
     * @param  \Magento\Framework\Module\Dir\Reader  $moduleDirectory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Module\Dir\Reader $moduleDirectory,
    ) {
        $this->moduleDirectory = $moduleDirectory;
        parent::__construct($context);
    }
 
    public function execute()
    {
        // Return view directory path
        $viewDir = $this->moduleDirectory->getModuleDir(
            \Magento\Framework\Module\Dir::MODULE_VIEW_DIR,
            'RH_Helloworld'
        );

        // Return etc directory path
        $etcDir = $this->moduleDirectory->getModuleDir(
            \Magento\Framework\Module\Dir::MODULE_ETC_DIR,
            'RH_Helloworld'
        );

        // Return i18n directory path
        $folderDir = $this->moduleDirectory->getModuleDir(
            \Magento\Framework\Module\Dir::MODULE_I18N_DIR,
            'RH_Helloworld'
        );
    }
}

You can use this above code in your block, helper and model file also. Here, I added code for view directory, etc directory and i18N directory path. If you want to other directory path then, you can pass value in first arguement and module name as second arguement.

Now, just remove generated & clean cache and check it.

That’s it !!!

I hope this blog is easy to understand about how to get module directory path in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

Tagged ,