Magento, Magento 2

How to Find out Version of Magento 2 Programmatically

How to Find out Version of Magento 2 Programmatically

In this tutorial, Today I will explain to how to find out version of Magento 2 Programmatically. As we all know, Magento is biggest open source e-commerce platform. They are upgrading their version with new functionalities and fix bugs. So, when we develop a module or any other custom functionality we may need to change some logics of code in file for specific versions.

At that time, we need to compare current version of Magento 2 in source code. Then, how we can get Magento 2 version programmatically

You may also like this :

1) Dependency Injection Method :

Using dependency injection method, You need to inject \Magento\Framework\App\ProductMetadataInterface class in the constructor of file. You can use this below code in your any PHP files.


/**
 * Created By : Rohan Hapani
 */

/**
 * @var \Magento\Framework\App\ProductMetadataInterface
 */
protected $productMetadata;
 
public function __construct(
    ...
    \Magento\Framework\App\ProductMetadataInterface $productMetadata
    ...
) {
    ...
    $this->productMetadata = $productMetadata;
    ...
}
 
public function getMagentoVersion()
{
    return $this->productMetadata->getVersion();
}
2) Object Manager Method :

You can also use object manager method in your source code file. But, I do not recommend to use object manager method. Always use dependency injection method.


/**
 * Created By : Rohan Hapani
 */
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();  
$productMetadata = $objectManager->get('\Magento\Framework\App\ProductMetadataInterface'); 
echo $productMetadata->getVersion();

That’s it !!

Now, Just Remove generated and clean cache.

I hope this blog is easy to understand about how to find out version of Magento 2 programmatically. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing !!

Tagged ,