← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 7 of 24

PHP Composer & Packages

What is Composer?

Composer is PHP's standard package manager, letting you declare which third-party libraries your project depends on and automatically download the right versions instead of copying code in by hand.

Example: What is Composer?

php
<?php
echo "Composer downloads the exact dependency versions your project declares.";
?>

Creating composer.json

composer.json sits in your project root and lists each dependency along with a version constraint, acting as the single source of truth for what your project needs to run.

Example: Creating composer.json

php
<?php
$composerJson = [
    "require" => [
        "monolog/monolog" => "^2.0"
    ]
];
echo json_encode($composerJson, JSON_PRETTY_PRINT);
?>

Installing Packages

Running composer install reads composer.json, resolves compatible versions for every dependency, and downloads them all into a vendor/ folder that your code then requires from.

Example: Installing Packages

php
<?php
// Run in terminal: composer install
echo "Downloads dependencies into vendor/ based on composer.json";
?>

Loading Composer's Autoloader

Including vendor/autoload.php at the top of your entry script wires up Composer's autoloader, which means every installed package's classes become available without a single manual require statement.

Example: Loading Composer's Autoloader

php
<?php
// require __DIR__ . '/vendor/autoload.php';
echo "One require statement makes every installed package's classes available";
?>

Managing Package Versions

Composer follows semantic versioning conventions: a caret (^1.2.0) allows any non-breaking update, while a tilde (~1.2.0) restricts updates to patch-level releases only, giving you fine control over how aggressively dependencies update.

Example: Managing Package Versions

php
<?php
$constraints = [
    "^1.2.0" => "any non-breaking update",
    "~1.2.0" => "patch-level updates only",
];
foreach ($constraints as $range => $meaning) {
    echo "$range: $meaning\n";
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.