Composer

La Lakshmi Priya Updated 21 Oct 2026
5 min read ·Lesson 174 of 174

What Is Composer?

In simple terms: Composer is PHP's package manager. Instead of downloading libraries by hand — a date library, a mailer, a PDF generator — you list them in a file, and Composer downloads them, together with everything they depend on, in compatible versions. It also generates an autoloader, so you can use all installed classes without writing require statements.

Technically: Composer is a dependency manager written in PHP. A project describes its requirements in composer.json; Composer resolves compatible versions (mostly from Packagist, the public package repository), installs them into vendor/, records the exact installed versions in composer.lock, and generates vendor/autoload.php (see Autoloading Classes and PSR-4 Autoloading). Practically every modern PHP project and framework uses Composer.


Installing Composer

Follow the instructions on https://getcomposer.org/download/, which verify the installer's checksum. On most systems, Composer is then available globally:

composer --version
Composer version 2.8.x

Starting a Project and Adding a Package

mkdir delivery-estimator && cd delivery-estimator
composer init --name=gocourse/delivery-estimator --type=project --no-interaction
composer require nesbot/carbon

composer require adds the package to composer.json, resolves its dependencies, downloads everything into vendor/, and writes composer.lock.

Using the Package

<?php
// estimate.php
require __DIR__ . '/vendor/autoload.php';

use Carbon\CarbonImmutable;

$ordered = CarbonImmutable::create(2026, 10, 15);   // a Thursday
$delivery = $ordered->addWeekdays(3);

echo "Ordered:  " . $ordered->format('l, d M Y') . "\n";
echo "Delivery: " . $delivery->format('l, d M Y') . "\n";
php estimate.php

Output

Ordered:  Thursday, 15 Oct 2026
Delivery: Tuesday, 20 Oct 2026

How It Works

  1. vendor/autoload.php registers Composer's autoloader for every installed package.
  2. Carbon\CarbonImmutable (an extension of DateTimeImmutable) is loaded automatically on first use.
  3. addWeekdays(3) skips the weekend: Friday, Monday, Tuesday.

The Project Files

composer.json — What You Want

{
    "name": "gocourse/delivery-estimator",
    "type": "project",
    "require": {
        "php": "^8.3",
        "ext-pdo": "*",
        "nesbot/carbon": "^3.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^11.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "scripts": {
        "test": "phpunit",
        "lint": "find src -name '*.php' -print0 | xargs -0 -n1 php -l"
    },
    "config": {
        "sort-packages": true
    }
}
KeyPurpose
requirePackages needed in production, plus the required PHP version and extensions (php, ext-pdo)
require-devPackages needed only for development (tests, static analysis)
autoloadHow your own classes are loaded (PSR-4 mapping)
scriptsNamed commands: composer test, composer lint
configComposer settings

composer.lock — What You Got

The lock file records the exact version (and source commit) of every installed package, including indirect dependencies. Everyone who runs composer install gets precisely the same versions.

vendor/ — The Installed Code

Generated by Composer. It is not committed to version control (add /vendor/ to .gitignore) and must never be edited by hand — changes would be lost on the next install.

File / FolderCommit to Git?
composer.jsonYes
composer.lockYes — for applications, so every environment uses identical versions
vendor/No

Version Constraints

ConstraintAllowsMeaning
^3.0>=3.0.0 <4.0.0Compatible updates (recommended; follows semantic versioning)
^1.2.3>=1.2.3 <2.0.0At least 1.2.3, no new major version
~1.2>=1.2 <2.0Like ^ for this case
~1.2.3>=1.2.3 <1.3.0Patch updates only
1.2.*>=1.2.0 <1.3.0Any 1.2 version
2.5.1Exactly 2.5.1Pinned (rarely needed; blocks security fixes)
*AnythingAvoid

Under semantic versioning, a major version (3 → 4) may break compatibility, minor versions add features, and patch versions fix bugs. The caret (^) accepts minor and patch updates but not breaking changes.


Essential Commands

CommandWhat It DoesWhen
composer installInstalls exactly the versions in composer.lockAfter cloning, in CI, on deployment
composer require vendor/packageAdds a packageAdding a dependency
composer require --dev vendor/packageAdds a development-only packageTest and analysis tools
composer updateUpdates packages within constraints and rewrites the lock fileDeliberately, followed by testing
composer update vendor/packageUpdates one package (and what it needs)Targeted updates
composer remove vendor/packageRemoves a packageCleaning up
composer outdated --directLists available newer versionsPlanning updates
composer auditReports installed packages with known security vulnerabilitiesRegularly and in CI
composer dump-autoloadRegenerates the autoloaderAfter changing autoload settings
composer validateChecks composer.jsonBefore committing changes

install vs update

  • composer install reads the lock file — reproducible and safe for servers.
  • composer update changes the lock file — run it on a development machine, test the results, and commit the new lock file.

Never run composer update on a production server.


Deploying With Composer

composer install --no-dev --optimize-autoloader --classmap-authoritative --no-interaction
OptionEffect
--no-devSkips development packages (test tools do not belong on production servers)
--optimize-autoloader (-o)Builds a class map for faster autoloading
--classmap-authoritativeLoads classes only from the class map — fastest, and no filesystem lookups
--no-interactionNever waits for input (essential in scripts)

Run composer audit in your deployment pipeline and fail the build if vulnerable packages are found.


Choosing Packages Wisely

Every dependency adds code you must trust and maintain. Before adding a package, check:

  • Maintenance: recent releases, responses to issues, supported PHP versions.
  • Popularity and quality: downloads on Packagist, tests, documentation.
  • License: compatible with your project (MIT, BSD, and Apache-2.0 are common).
  • Size of the dependency tree: a small helper should not pull in dozens of packages.

Popular, well-maintained examples include monolog/monolog (logging), symfony/mailer (email), guzzlehttp/guzzle (HTTP), vlucas/phpdotenv (environment files), nesbot/carbon (dates), and phpunit/phpunit (testing).


Common Mistakes

Committing vendor/

Effect: Huge repositories and merge conflicts.

Fix: Commit composer.json and composer.lock; run composer install.

Not Committing composer.lock for Applications

Effect: Servers install different versions than those tested.

Fix: Commit the lock file.

Running composer update in Production

Effect: Untested versions go live.

Fix: Update in development, test, commit the lock file, then composer install on servers.

Editing Files in vendor/

Effect: Changes disappear on the next install.

Fix: Extend or configure packages; contribute fixes upstream or use patches deliberately.

Ignoring Security Advisories

Effect: Known vulnerabilities remain in production.

Fix: Run composer audit regularly and update affected packages.


Best Practices

  • Manage all third-party code with Composer and load it through vendor/autoload.php.
  • Use caret constraints, commit composer.lock, and never commit vendor/.
  • Declare the PHP version and required extensions in require.
  • Deploy with composer install --no-dev --optimize-autoloader and audit dependencies regularly.
  • Keep dependencies few, maintained, and up to date.

Official reference: https://www.php.net/manual/en/install.composer.intro.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer
Ask about this post
AI Ask about this post

Ask questions about Composer and get answers drawn from it.

Signed-in readers only.