🎼 Composer
Composer is a command line package manager for PHP libraries. This note contains basic Composer usage tips.
composer -V
# Composer version 0c85ca426d6e8235366340f29ad0e6aab1747b83 2014-05-19 10:17:07
Basic commands:
composer init
: Creates a newcomposer.json
file for a new project in the current directory.composer install
: Downloads and installs dependencies fromcomposer.json
andcomposer.lock
intovendor
Createscomposer.lock
if it doesn't exist; it contains specific package versions you are using.composer update
: Updates all packages defined incomposer.lock
.composer require vendor-name/package-name
: Installs a package and writes the dependency tocomposer.json
You specify your project's PHP dependencies in composer.json
file.
{
"name": "vendor-name/project-or-library-name",
"authors": [
{
"name": "Ruksi",
"email": "me@ruk.si"
}
],
"require": {
"php": ">=5.3.2",
"nesbot/carbon": "1.13.0"
}
}
If you require a feature, there probably is a package for that. Full list of Composer packages is available at Packagist. The packages I use frequently are listed at PHP libraries note.
Know what to commit. Always commit composer.json
and composer.lock
files.
composer.json
contains original definitions of your dependencies.composer.lock
contains exact version of your dependencies and is created on the firstcomposer install
and rewritten on eachcomposer update
.- You usually don't want to commit the
vendor/
directory.
Never do composer update
in production. It will overwrite your lock-file and possibly cause some dependencies to update, potentially leading to problems.
- In development: composer install, composer update
- In production: composer install
Include the autoloader. You must include composer autoloader to use the installed packages.
require 'vendor/autoload.php';
$log = new Monolog\Logger('name');
Extend the autoloader. You can add your own directories to autoloader by editing composer.json
. You have to run another composer install
after each change.
{
...
"autoload": {
"psr-4": {"YourNamespace\\": "your-src/"}
}
}
You can manipulate autoloader at runtime. Useful for e.g. unit testing.
$loader = require 'vendor/autoload.php';
$loader->add('YourNamespace\\Test\\', __DIR__);
Sources
- Composer
- Laracon 2013 talks