Tag: Composer

PHP: get version details from composer.json

code editor with html

Let’s say we have a composer.json file as follows:

{
    "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 the projects composer.json file.

Get details about the root package

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

$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:

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

Get details about installed packages

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

Version of an installed package

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

Install path of an installed package

$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

 

Composer global verwenden

In der Dokumentation zu Composer wird erläutert, wie man global auf composer.phar zugreifen kann, ohne permanent php composer.phar ins Terminal eingeben zu müssen:

[…]

You can place the Composer PHAR anywhere you wish. If you put it in a directory that is part of your PATH, you can access it globally. On unix systems you can even make it executable and invoke it without directly using the php interpreter.

After running the installer following the Download page instructions you can run this to move composer.phar to a directory that is in your path:

mv composer.phar /usr/local/bin/composer

Note: If the above fails due to permissions, you may need to run it again with sudo.

Note: On some versions of OSX the /usr directory does not exist by default. If you receive the error “/usr/local/bin/composer: No such file or directory” then you must create the directory manually before proceeding: mkdir -p /usr/local/bin.

Note: For information on changing your PATH, please read the Wikipedia article and/or use Google.

Now just run composer in order to run Composer instead of php composer.phar.