Dependency management
Composer is a tool for dependency management in PHP. You declare the libraries your project depends on and it will install (update) them for you.
sudo apt update
sudo apt install wget php-cli php-zip unzip curl
curl -sS getcomposer.org/installer |php
Composer.json
To use Composer a project simply need a composer.json file in its root directory. This file defines the dependencies of the project.
{
"require": {
"nesbot/carbon": "2.12.*"
}
}
Require
We can edit composer.json manually, or we can use commands (require/update).
mkdir /var/www/html/composer-test
cd /var/www/html/composer-test
composer require nesbot/carbon
# Failed to open stream: Permission denied
# Cannot create cache directory /home/catalin/.composer/cache/
# Avoid sudo when running composer.
sudo chown -R myuser.myuser composer-test
sudo chown -R catalin.catalin /home/catalin/.composer/
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
printf("Now: %s", Carbon::now()); // Now: 2020-05-08 10:34:49
printf("Lastweek: %s", Carbon::now()->subWeek());
Update packages
Composer will update the package if newer version found. Also, version constraint match with the one specified in the composer.json
composer outdated
composer clearcache
composer update
Self update
To upgrade Composer on Ubuntu, you can use the following command in your terminal:
composer --version
Composer version 2.2.6 2022-02-04 17:00:38
sudo composer self-update
composer --version
Composer version 2.6.6 2023-12-08 18:32:26
Last update: 267 days ago