composer.json is the heart of a Composer project. It is a JSON file in your project’s root folder that lists what your project needs.
Create one
composer init
Composer asks a few questions (name, description, author, packages) and writes the file. You can also create the file by hand.
A realistic example
{
"name": "acme/blog-app",
"description": "A small blog application",
"type": "project",
"require": {
"php": "^8.2",
"league/commonmark": "^2.0"
},
"require-dev": {
"phpunit/phpunit": "^11.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"test": "phpunit"
},
"config": {
"sort-packages": true
}
}
The main fields
| Field | Meaning |
|---|---|
name | vendor/project, in lowercase. Required for packages you publish |
description | A short sentence about the project |
type | project, library, metapackage and so on |
require | Packages the project needs to run (including the PHP version) |
require-dev | Packages needed only for development (testing, style checks) |
autoload | How to load your classes |
autoload-dev | Autoloading for test code |
scripts | Shortcuts for commands. composer test runs phpunit |
config | Composer’s own settings |
require and the PHP version
Putting "php": "^8.2" in require tells Composer that your project needs PHP 8.2 or newer. Composer then refuses to install packages that do not work on that version, and warns you if you run it on an older PHP.
Version constraints
"^2.0" is a constraint: any version from 2.0.0 up to (but not including) 3.0.0. Managing Dependencies explains them.
The file must be valid JSON
JSON is strict: double quotes only, no trailing commas, no comments. Check a file with:
composer validate
Backslashes in JSON
In the autoload section, the namespace ends with a backslash. In JSON, a backslash must be written twice: "App\\".
Commit or ignore?
| File or folder | Put in Git? |
|---|---|
composer.json | Yes |
composer.lock | Yes for applications (see composer.lock) |
vendor/ | No. Add it to .gitignore. It is rebuilt with composer install |
Let Composer edit it
composer require package instead of editing require by hand. Composer picks a sensible version constraint and updates the lock file too.