Hello Magento Friends,
In today’s blog, I will explain How to Create a Directory Programmatically in Magento 2.
Directories in Magento 2 serve as a structured storage mechanism for various files, modules, customizations, caching, and logging. They play a crucial role in organizing, managing, and optimizing the functionality and performance of a Magento 2 store.
So let’s learn how to programmatically create a directory in Magento 2.
Steps to Create a Directory Programmatically in Magento 2:
Step 1: First, create a CreateDirectory.php file inside the etc folder.
app\code\Vendor\Extension\Helper
Then add the below code
<?php namespace Vendor\Extension\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\Filesystem; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Filesystem\Directory\WriteInterface; class CreateDirectory extends AbstractHelper { protected $file; protected $newCreateDirectory; public function __construct( Filesystem $file ) { $this->newCreateDirectory = $file->getDirectoryWrite(DirectoryList::VAR_DIR); } public function createDirectory() { $directoryPath = "magecomp"; $newCreateDirectory = false; try { $newCreateDirectory = $this->newCreateDirectory->create($directoryPath); } catch (FileSystemException $e) { throw new LocalizedException( __("you can't create directory", $directoryPath) ); } return $newCreateDirectory; } }
Conclusion:
So you can easily create a directory programmatically in Magento 2. You can even Delete a Directory in Magento 2 Programmatically. If you have any doubt about the above step, ask me through the comment box without any hesitation. Share the article with your friends and stay updated with us.
Happy Coding!
Hello
Please use double quotes for the main string. The line below contains an error:
__(‘you can’t create directory’, $directoryPath)
Thanks.
Thanks for your suggestion, we have updated it accordingly.