Magento 2 : How to get Custom module's 'web' directory path/Get custom module image directory path
Use code below to get module directory path
class CustomModel
{
/**
* @var \Magento\Framework\Module\Dir\Reader
*/
protected $moduleReader;
/**
* @param \Magento\Framework\Module\Dir\Reader $moduleReader
*/
public function __construct(
\Magento\Framework\Module\Dir\Reader $moduleReader
) {
$this->moduleReader = $moduleReader;
}
public function getDirectory()
{
$viewDir = $this->moduleReader->getModuleDir(
\Magento\Framework\Module\Dir::MODULE_VIEW_DIR,
'Vendor_Module'
);
return $viewDir . '/frontend/web/images';
}
}
but if you need to check content static file I'd recommend you to use this way...
class CustomModel
{
/**
* @var \Magento\Framework\View\Asset\Repository
*/
protected $assetRepository;
/**
* @param \Magento\Framework\View\Asset\Repository $assetRepository
*/
public function __construct(
\Magento\Framework\View\Asset\Repository $assetRepository
) {
$this->assetRepository = $assetRepository;
}
public function getMyFilePath()
{
$fileId = 'Vendor_Module::images/myimage.png';
$params = [
'area' => 'frontend'
];
$asset = $this->assetRepository->createAsset($fileId, $params);
try {
return $asset->getSourceFile();
} catch (\Exception $e) {
return null;
}
}
}
You can also use Magento\Framework\Module\Dir
Class to get Directory path of the module:
EXample:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$dir = $objectManager->get('Magento\Framework\Module\Dir');
/*Retrieve full path to a directory of certain type within a module*/
echo $dir->getDir('Magento_Customer');
echo $dir->getDir('Magento_Customer','Controller');
Syntax:
getDir('Module_Name','Directories');
/*getDir method not allow to read type of module's directory except these*/
const MODULE_ETC_DIR = 'etc';
const MODULE_I18N_DIR = 'i18n';
const MODULE_VIEW_DIR = 'view';
const MODULE_CONTROLLER_DIR = 'Controller';