Site icon MageComp Blog

How to get Module Version Programmatically in Magento 2

How to get Module Version Programmatically in Magento 2

Hello Magento Friends,

In our today’s blog, we will learn How to get Module Version Programmatically in Magento 2.

In Magento 2, modules are essential components that add functionality to the platform. It’s important to keep track of module versions, as updates and compatibility can affect your store’s performance.

You can display the module list in Magento 2 to know which modules are installed on your store.

Let’s find the steps to fetch the module version programmatically in Magento 2.

Steps to get Module Version Programmatically in Magento 2:

Step 1: Create a file in your Magento root directory at the below path. 

magento_root_directory\ModuleVersionCheck.php

And add the below code

<?php
use Magento\MediaStorage\Helper\File\Storage\Database;
use Magento\Framework\AppInterface;
use Magento\Framework\Component\ComponentRegistrar;

try
{
    require_once __DIR__ . '/app/bootstrap.php';
}
catch (\Exception $e)
{
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try
{
    $moduleName = 'Vendor_Extension';  /** Your extension name **/
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $appState = $objectManager->get('\Magento\Framework\App\State');
    $appState->setAreaCode('frontend');
    echo getMagentoModuleVersion($moduleName);
}
catch(\Exception $e)
{
    print_r($e->getMessage());
}

function getMagentoModuleVersion(string $moduleName): string
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $componentreg = $objectManager->get('\Magento\Framework\Component\ComponentRegistrarInterface');
    $register=$objectManager->get('\Magento\Framework\Filesystem\Directory\ReadFactory');
    
    $path = $componentreg->getPath(
        ComponentRegistrar::MODULE,
        $moduleName
    );
    $directoryRead = $register->create($path);
    $composerJsonData = '';
    if ($directoryRead->isFile('composer.json')) {
        $composerJsonData = $directoryRead->readFile('composer.json');
    }
    $data = json_decode($composerJsonData);

    return !empty($data->version) ? $data->version : '';
}

Conclusion:

Being able to programmatically fetch module versions in Magento 2 is valuable for monitoring your store’s extensions and ensuring compatibility. By following the steps outlined in this blog post, you’ll be able to retrieve and display module versions with ease, helping you to maintain a well-functioning and up-to-date Magento store.

Happy Coding!

Exit mobile version