How To Install A Specific Package Version Using Composer?

Published October 21, 2024

Problem: Installing Specific Package Versions

Composer is a dependency management tool for PHP. Sometimes you need to install a specific version of a package. This can be needed for compatibility or to keep consistency across different environments. Installing the correct package version is important for project development and deployment.

Solution: Using Version Constraints with Composer

The Composer Require Command with Version Specification

To install a specific version of a package using Composer, use the composer require command with a version constraint. The syntax for this command is:

composer require vendor/package:version

For example, to install version 0.10.2 of the refinery29/test-util package, use:

composer require refinery29/test-util:0.10.2

This command tells Composer to install the exact version you specified, not the latest version.

Understanding Composer Version Constraints

Composer offers several ways to specify version constraints:

  1. Exact version numbers: You can specify an exact version number, as shown in the previous example.

  2. Version ranges: You can use comparison operators to define a range of acceptable versions. For example:

    • >=1.0: Version 1.0 or higher
    • >1.0 <2.0: Higher than 1.0 but lower than 2.0
    • >=1.0 <1.1 || >=1.2: Version 1.0 or higher, but lower than 1.1, or 1.2 or higher
  3. Wildcard versions: You can use the asterisk (*) as a wildcard to match any version number in that position. For example:

    • 1.0.*: Any version that starts with 1.0
    • 1.*: Any version that starts with 1

By using these version constraints, you can control which version of a package Composer installs, giving you more options in managing your project's dependencies.

Tip: Use Caret (^) for Flexible Version Constraints

When you want to allow updates to a package but only for minor and patch versions, use the caret (^) operator. For example, ^1.2.3 allows updates to any version from 1.2.3 up to, but not including, 2.0.0. This is useful for getting bug fixes and new features while avoiding potentially breaking changes in major versions.