code editor with html

PHP: get version details from composer.json

Written by

in

Composer is a tool for dependency management in PHP. It allows PHP developers to easily manage and install the libraries and packages their projects depend on. Composer simplifies the process of including external libraries into PHP projects and helps manage versioning and dependencies.

The packages that are required for your project are located in a composer.json file. Let’s say we have a composer.json file as follows:

JSON
{
    "name": "mixable/blog",
    "description": "mixable.blog",
    "homepage": "https://mixable.blog",
    "version": "4.0.1",
    "type": "project",
    "require": {
        "php": "^8.x",
        "vendor/package": "^4.3",
        ...
    }
}

When using this file to manage the packages of an app, it might be necessary to check for the version of your app. This is possible by using the Composer class \Composer\InstalledVersions. The class provides different methods to access the details of your projects composer.json file.

Get details of the root package

Details about the root package are available through the getRootPackage() method:

PHP
$package = \Composer\InstalledVersions::getRootPackage();

This method returns an array with the following details:

name: string
version: string
reference: string
pretty_version: string
aliases: string[]
dev: bool
install_path: string
type: string

To get the apps version, you can use:

PHP
$version = \Composer\InstalledVersions::getRootPackage()['version'];

Get details of installed packages

There is a number of methods that provide additional information about the installed packages. Some examples:

Version of an installed package

PHP
$version = \Composer\InstalledVersions::getVersion('vendor/package');

Install path of an installed package

PHP
$installPath = \Composer\InstalledVersions::getInstallPath('vendor/package');

A detailed description of all methods is available at https://getcomposer.org/doc/07-runtime.md#installed-versions.

Photo by Ilya Pavlov on Unsplash


Comments

Leave a Reply

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