Composer

Ma Mahalakshmi V Updated 14 Nov 2026
5 min read ·Lesson 241 of 255

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 Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays 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 array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types 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 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 MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about Composer and get answers drawn from it.

Signed-in readers only.