Magento 2 – Get Custom Module’s Web Directory Path

directorymagento-2.1magento2

I have created a custom module in which I want to check if a (image)file exists in my view/frontend/web/images folder.

I have checked this answer but in only shows how to get Magento's directory paths.

How can I get full path for my module's directory which will support with Magento 2's static content deploy feature?

EDIT

As per Rakesh's answer I can use below code.

$mediapath = $this->_filesystem->getDirectoryRead(DirectoryList::APP)->getAbsolutePath();
$modulePath = echo $mediapath.'code/Packagename/Modulename/view/frontend/web/images';

Is there any other alternative to this approach?

Best Answer

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;
        }
    }
}
Related Topic