How to Get Root Directory Path in Magento 2

While building your custom extension, you will usually need path to your extensions files. If you need to root the directory path in your custom module then, you need to inject \Magento\Framework\App\Filesystem\DirectoryList class in your construct.

So, Let’s check the below steps with output.

<?php
namespace Kaushik\Helloworld\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
class Data extends AbstractHelper
{

/**
 * @var \Magento\Framework\App\Filesystem\DirectoryList
 */
protected $dir;

public function __construct(
    ...
    \Magento\Framework\App\Filesystem\DirectoryList $dir,
    ...        
) {
    ...
    $this->dir = $dir;
    ...
}

public function getRootPath()
{
    return $this->dir->getRoot(); // Output : /var/www/html
}
}

However, If you want to get a media, var, pub, etc. directory path then, you can use the below codes to get the appropriate directory path.

$this->dir->getPath('pub'); // Output : /var/www/html/pub
$this->dir->getPath('media'); // Output : /var/www/html/pub/media
$this->dir->getPath('lib_internal'); // Output : /var/www/html/lib/internal
$this->dir->getPath('log'); // Output : /var/www/html/var/log
$this->dir->getPath('generated'); // Output: /var/www/html/generated

That’s it !!!

In other words, You can use the above code in your function based on your requirement.

Leave a Reply