Skip to main content

Composer is a dependency manager for PHP. It allows you to declare the libraries your project depends on and it will manage them for you.

To install composer you can run these commands and execute them in your terminal window.

Note that the hash-file changes per version! For the latest install instructions go to: Composer download page

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

You should end up with a file composer.phar. To use it you can run the command:

php composer.phar

But this is not very handy and you want to be able to just type: composer. In order to do that you can move the composer.phar file for example to /usr/local/bin location (Mac) and renamed it to composer. The command to achieve this is:

mv composer.phar /usr/loca/bin/composer

If you don't have access to /usr/local/bin/ you can also copy it to the ~/bin/ folder in the home directory. On Debian system in the .profile there are a couple of lines of code that will add this directory to the path.

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

To get composer packages you can browse https://packagist.org/. For example if you type in monolog, in the results you will see a packaged called monolog/monolog. You can install this package by executing:

composer require monolog/monolog

This command will pull in all needed dependencies. In the directory where you executed the composer command you will find composer.json where the monolog package is listed. If you have this file in a separate directory you can execute:

composer install

and it will install the package listed in it. In the vendor/ directory you can find all downloaded dependencies. There is also a file with the name autoload.php. In you require this file on top of your php script it will let you user all the functions and classes provided by this package. In the case of monolog you can use the example below to create an app.log file with a warning log entry called Foo.

<?php

require __DIR__ . '/vendor/autoload.php';

$log = new Monolog\Logger('name');
$log->pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::WARNING));
$log->addWarning('Foo');

It is also possible to create a new project using composer. In comparison to composer require it will clone the whole project repository to a directory you specify. In case of monolog it will clone the git repository located on https://github.com/Seldaek/monolog. The command do this is:

composer create-project monolog/monolog monolog-project-dir

Tags

Category