Skip to content

Instantly share code, notes, and snippets.

@0-Sony
Created July 6, 2023 10:14
Show Gist options
  • Save 0-Sony/457da0206da7366588ae857e2fcf18b0 to your computer and use it in GitHub Desktop.
Save 0-Sony/457da0206da7366588ae857e2fcf18b0 to your computer and use it in GitHub Desktop.
Magento 2 : Get File Content from Specific Module
<?php
declare(strict_types=1);
namespace MyNamespace\MyModule\Setup\Patch\Data;
use Magento\Framework\App\Config\Storage\WriterInterface;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Module\Dir;
use Magento\Framework\Module\Dir\Reader;
use Magento\Framework\Setup\Patch\DataPatchInterface;
class GetFileContentFromModule implements DataPatchInterface
{
private const FILE = 'my_file.txt';
/** adapt the constructor according your php version */
public function __construct(
private readonly WriterInterface $writer,
private readonly File $driverFile,
private readonly Reader $moduleReader,
) {
}
/**
* @inheritDoc
*/
public static function getDependencies(): array
{
return [];
}
/**
* @inheritDoc
*/
public function getAliases(): array
{
return [];
}
/**
* @inheritDoc
* @throws FileSystemException
*/
public function apply(): void
{
/**
* For instance, your file is under this location MyNamespace\MyModule\Setup\Model\my_file.txt
*/
$modulePath = $this->moduleReader->getModuleDir(Dir::MODULE_SETUP_DIR, 'MyNamespace_MyModule');
$modulePath .= DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR;
$localFilePath = $modulePath . self::FILE;
$fileContent = $this->driverFile->fileGetContents($localFilePath);
/**
* Do your stuff with File Content.
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment