Magento 2 get base directory

Today we discuss about Magento 2 get base directory .This tutorial include how to get base directory like media and other directories. There are two ways to do it. One is factory method and other is use object manager. So let start with our example.

Factory Method

In this example we will get base directory of media.

<?php
/**
* Simple Hello World Module
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com
*
*/

namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $directoryList;

public function __construct(
\Magento\Framework\App\Filesystem\DirectoryList $directoryList
) {
    $this->directoryList=$directoryList
}
public function getbaseDir()
{
   return $this->_directorylist->getPath('media');

}

}

Object Manager

In this example we will get base directory of media. Using object manager is not recommended.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$dir = $objectManager->create('Magento\Framework\App\Filesystem\DirectoryList');
$mediaPath = $dir->getPath('media');

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply