Programmatically Find Out Installed Magento 2 Version

As we all know that Magento is the biggest content management system. They are upgrading their version every time with lots of features and fixes. So as a developer, many times we may require to get the installed Magento version in our code programmatically. Here is the blog which will help you to get the installed Magento version programmatically.

In the following post, I have provided the example for both Dependency Injection (DI) and Object Manager methods. But Magento recommends using the dependency injection method instead of the object manager.

Using Dependency Injection (DI):

Here is the example code to get the installed Magento 2 version using dependency injection. While using the dependency injection method, we might need to inject the object of \Magento\Framework\App\ProductMetadataInterface class in the constructor of our module’s class as follows,

protected $productMetadata;

public function __construct(
	...
	\Magento\Framework\App\ProductMetadataInterface $productMetadata
	...
) {
	...
	$this->productMetadata = $productMetadata;
	...
}

public function getCurrentMagentoVersion()
{
	return $this->productMetadata->getVersion();
}

Using Object Manager:

Here is the example code to get the installed Magento 2 version using object manager.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();  
$productMetadata = $objectManager->get('\Magento\Framework\App\ProductMetadataInterface'); 
echo $productMetadata->getVersion();

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *