Menu Close

    How to get composer.json data in block in magento 2

    In this blog, we will try to learn about getting the composer.json data saved in Magento 2 module.

    In Magento 2 we define the composer.json file for the particular module, which will define the module versioning and dependencies of the module, and so on.

    Now, to get saved information from the composer.json file we will see the file in the file path \Magento\Framework\Component\ComponentRegistrarInterface
    Here we will find the method named as
    create($path) which will help us to get the data in a user-defined block file.

    Now, we will see how we can achieve this.

    class ComposerVersion extends \Magento\Config\Block\System\Config\Form\Field {
        public function __construct(
            \Magento\Framework\View\Asset\Repository $assetRepo,
            \Magento\Backend\Block\Template\Context $context,
            \Magento\Framework\App\DeploymentConfig $deploymentConfig,
            \Magento\Framework\Component\ComponentRegistrarInterface $componentRegistrar,
            \Magento\Framework\Filesystem\Directory\ReadFactory $readFactory,
            array $data = []
        ) {
            $this->_assetRepo = $assetRepo;
            $this->deploymentConfig = $deploymentConfig;
            $this->componentRegistrar = $componentRegistrar;
            $this->readFactory = $readFactory;
            parent::__construct($context, $data);
        public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element) {
            $moduleName = 'Vendor_Module';
            $path = $this->componentRegistrar->getPath(
            $directoryRead = $this->readFactory->create($path);
            $composerJsonData = $directoryRead->readFile('composer.json');
            $data = json_decode($composerJsonData);
            return $data;

    Now you can use this block as per your requirement.

    Start your headless eCommerce
    Read More
    . . .
    Discuss on Helpdesk

    Leave a Comment

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

    Be the first to comment.

    Back to Top