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');
}
}
/**
* 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');
$dir = $objectManager->create('Magento\Framework\App\Filesystem\DirectoryList');
$mediaPath = $dir->getPath('media');