CodeBlanks Logo Icon CodeBlanks

Adding packages with require

PHP course · Advanced · Lesson 36/92

Learn to add a new package with composer require and version constraints.

composer require and version constraints

The composer require monolog/monolog command adds a new package to your project. A version constraint follows the package name; for example composer require monolog/monolog:^3.5 installs 3.5 and any later 3.x version.

The ^ sign is called caret, the ~ sign is called tilde. These two are the most common version constraints and decide which sub-versions of a package are accepted.

The tilde ~ constraint

The tilde ~ sign resembles caret but gives a narrower range. The ~1.2 constraint accepts 1.2 and any later 1.x; just like ^1.2. The difference shows up at the patch level.

~1.2.3 accepts only 1.2.x versions; ^1.2.3 accepts all 1.x.x. So tilde pins the patch version, caret keeps the major version.

Exercise Version constraint resolver

Write a parseConstraint(string $c): string function. If the constraint starts with ^ return "caret", with ~ return "tilde", if it is * return "any", otherwise return "exact". Call four constraints (^3.5, ~7.8, *, 3.0.0) in turn and print in the form monolog/monolog: ^3.5 -> caret.

Show example solution
string { if (strpos($c, "^") === 0) { return "caret"; } if (strpos($c, "~") === 0) { return "tilde"; } if ($c === "*") { return "any"; } return "exact"; }. Define $deps = ["monolog/monolog" => "^3.5", "guzzlehttp/guzzle" => "~7.8", "symfony/console" => "*", "psr/log" => "3.0.0"];. Print with foreach ($deps as $pkg => $ver) { echo $pkg . ": " . $ver . " -> " . parseConstraint($ver) . "\n"; }.
Example solution:
<?php
function parseConstraint(string $c): string {
    if (strpos($c, "^") === 0) { return "caret"; }
    if (strpos($c, "~") === 0) { return "tilde"; }
    if ($c === "*") { return "any"; }
    return "exact";
}
$deps = ["monolog/monolog" => "^3.5", "guzzlehttp/guzzle" => "~7.8", "symfony/console" => "*", "psr/log" => "3.0.0"];
foreach ($deps as $pkg => $ver) {
    echo $pkg . ": " . $ver . " -> " . parseConstraint($ver) . "\n";
}

Test yourself

  1. What does the ^3.5 constraint accept?

    • Only 3.5.0
    • 3.5 and any later 3.x
    • 4.x and later
    • All versions older than 3.5
    Show answer

    3.5 and any later 3.x — Correct. ^3.5 (caret) accepts 3.5 and any later 3.x.

  2. Complete the caret constraint

    <?php
    // Version constraint: 7.8 and any later 7.x
    $cfg = ["ver" => "____7.8"];
    echo $cfg["ver"] . "\n";
    
    Show answer
    <?php
    // Version constraint: 7.8 and any later 7.x
    $cfg = ["ver" => "^7.8"];
    echo $cfg["ver"] . "\n";
    
  3. Match the version constraints

    ^1.2.3
    Accepts 1.x.x
    ~1.2.3
    Accepts 1.2.x
    1.2.3
    Only 1.2.3
    *
    Any version

All lessons in Advanced