Magento 2

How to Create Dynamic File while installing Extensions in Magento 2

The Magento extension is made up of several files that work together to serve a purpose for it made. This extension either overrides default Magento files or works separately to enhance default Magento functionality by extending the native code.

Every time, when we install the extension inside Magento store, it requires some of the user input before installation and saves to file instead of a database. These files are generally known as a dynamic file which contains dynamic or you can say changeable values instead of any static value. Recently while creating an extension we came across the same requirements.

We need to create one file for our requirement of creating a dynamic file using InstallData class inside our Module using below code.
app\code\Vendor\Extension\Setup\InstallData.php

<?php
namespace Vendor\Extension\Setup;
use Magento\Eav\Model\Config;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Storage\WriterInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Module\Dir;
 
class InstallData implements InstallDataInterface
{
         
   const XML_PATH_CUSTOMER_FILENAME = 'customer/privacy/cipher_filename';
 protected $scopeConfig;
 protected $configWriter;
 protected $directoryList;
 protected $cacheTypeList;
 protected $eavConfig;
         
        public function __construct
        (
      ScopeConfigInterface $scopeConfig,
      WriterInterface $configWriter,
      TypeListInterface $cacheTypeList,
      DirectoryList $directoryList,
      Config $eavConfig,
  Reader $moduleReader
 )
 {
     $this->scopeConfig = $scopeConfig;
     $this->configWriter = $configWriter;
     $this->cacheTypeList = $cacheTypeList;
     $this->directoryList = $directoryList;
     $this->eavConfig = $eavConfig;
 }
 
 public function install( ModuleDataSetupInterface $setup, ModuleContextInterface $context )
 {
     $setup->startSetup();
     $dir = $this->getDatabaseDirectory();
     if (!is_dir($dir)) {
         mkdir($dir, 0700, true);
     }
     $fileName = $this->scopeConfig->getValue(self::XML_PATH_CUSTOMER_FILENAME);
     if (strlen($fileName) == 0) {
         $fileName = md5(microtime(true) . rand(0, 10000));
            $this->configWriter->save(self::XML_PATH_CUSTOMER_FILENAME, $fileName);
            $this->cacheTypeList->cleanType('config');
     }
     $file = $dir . '/' . $fileName . '.php';
     if (!is_file($file)) {
         file_put_contents($file, 'Hello Vendor');
         chmod($file, 0700);
     }
    
     $setup->endSetup();
 }
 
        public function getDatabaseDirectory()
        
 {
      $viewDir = $this->moduleReader->getModuleDir(
   \Magento\Framework\Module\Dir::MODULE_VIEW_DIR,
   'Vendor_Extension'
      );
             return $viewDir . '/frontend/web';
 }
 
}

Also, you can play manipulate with these codes according to your need of creating dynamic file while creating an extension.

Lastly, hit that stars if this code works for you and comment down below if you face any issue while using this code. Happy Coding!

Click to rate this post!
[Total: 2 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

2 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

4 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

4 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

5 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

6 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago