Skip to content

PHP Tutorial Composer

composer.json

Lesson 249 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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

terminal
BASH
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

data.json
JSON
{
    "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

FieldMeaning
namevendor/project, in lowercase. Required for packages you publish
descriptionA short sentence about the project
typeproject, library, metapackage and so on
requirePackages the project needs to run (including the PHP version)
require-devPackages needed only for development (testing, style checks)
autoloadHow to load your classes
autoload-devAutoloading for test code
scriptsShortcuts for commands. composer test runs phpunit
configComposer’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:

terminal
BASH
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 folderPut in Git?
composer.jsonYes
composer.lockYes for applications (see composer.lock)
vendor/No. Add it to .gitignore. It is rebuilt with composer install
lightbulb
Let Composer edit it
Use composer require package instead of editing require by hand. Composer picks a sensible version constraint and updates the lock file too.