Maintaining a well-organized the composer.json file helps keep PHP projects easier to manage. Sorting packages alphabetically in the require and require-dev sections improves readability and reduces unnecessary merge conflicts when multiple branches introduce new dependencies. This tutorial explains how to sort PHP packages in requirements section using Composer.
Composer includes a built-in option that can handle package sorting automatically. To enable automatic sorting, add the sort-packages option inside the config section of the composer.json.
{
"name": "company/my-project",
"description": "Project description",
"type": "project",
"license": "MIT",
"require": {
"symfony/serializer": "^7.4",
"symfony/console": "^7.4",
"symfony/http-client": "^7.4"
},
"config": {
"sort-packages": true
}
}
After enabling this setting, Composer will place newly added packages in alphabetical order instead of appending them to the bottom of the list. To re-sort existing entries, require a package that is already present in the project. For example:
composer require symfony/serializer=^7.4
Once the command completes, the dependencies will be reordered automatically. Example:
{
"name": "company/my-project",
"description": "Project description",
"type": "project",
"license": "MIT",
"require": {
"symfony/console": "^7.4",
"symfony/http-client": "^7.4",
"symfony/serializer": "^7.4"
},
"config": {
"sort-packages": true
}
}
Composer also supports sorting packages without permanently enabling the configuration option. This can be done by passing the --sort-packages option directly in the command. For example:
composer require --sort-packages symfony/serializer=^7.4
Keeping dependency lists sorted is considered a good practice for collaborative projects, especially when multiple developers frequently add or update Composer packages.
Leave a Comment
Cancel reply