How can I read my extension's version in Magento 2?

You could inject Magento\Framework\Module\ModuleListInterface in to your module helper class and then have a helper function to get it. Something like;

<?php

namespace [Vendor]\[ModuleName]\Helper;

use Magento\Framework\App\Helper\Context;
use Magento\Framework\Module\ModuleListInterface;

class Data extends AbstractHelper
{
    const MODULE_NAME = 'xxx';

    protected $_moduleList;

    public function __construct(
        Context $context,
        ModuleListInterface $moduleList)
    {
        $this->_moduleList = $moduleList;
        parent::__construct($context);
    }

    public function getVersion()
    {
        return $this->_moduleList
            ->getOne(self::MODULE_NAME)['setup_version'];
    }
}

Sorry, i haven't had time to put this in to code and test it thoroughly.


Try following way:

$moduleInfo =  $this->_objectManager->get('Magento\Framework\Module\ModuleList')->getOne('SR_Learning'); // SR_Learning is module name

print_r($moduleInfo);

Output

Array ( [name] => SR_Learning [setup_version] => 2.0.0 [sequence] => Array ( ) )

It's bit different but not that hard.

All you have to do is inject the \Magento\Framework\Module\ModuleListInterface via helper constructor and use that in custom function.

Here is the full working code taken from https://github.com/MagePsycho/magento2-easy-template-path-hints

<?php
namespace MagePsycho\Easypathhints\Helper;

/**
 * Utility Helper
 *
 * @category   MagePsycho
 * @package    MagePsycho_Easypathhints
 * @author     Raj KB <[email protected]>
 * @website    http://www.magepsycho.com
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var \Magento\Framework\Module\ModuleListInterface
     */
    protected $_moduleList;

    /**
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\Framework\Module\ModuleListInterface $moduleList
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\Module\ModuleListInterface $moduleList
    ) {
        $this->_moduleList              = $moduleList;

        parent::__construct($context);
    }



    public function getExtensionVersion()
    {
        $moduleCode = 'MagePsycho_Easypathhints'; #Edit here with your Namespace_Module
        $moduleInfo = $this->_moduleList->getOne($moduleCode);
        return $moduleInfo['setup_version'];
    }
}