Getting Started with Composer: A Complete Guide

Published on  

8 min read

Getting Started with Composer: A Complete Guide

In this guide, we'll walk you through everything you need to know to get started with Composer.

Are you a PHP developer looking for a way to manage your project's dependencies? If so, Composer might be the tool for you! Composer is a popular package manager for PHP that allows you to easily manage your project's dependencies and third-party libraries.

What is Composer?

Composer is a package manager for PHP that allows you to easily manage your project's dependencies. It was created in 2011 by Nils Adermann and Jordi Boggiano and has since become the go-to tool for PHP developers.

With Composer, you can easily install, update, and remove dependencies for your project. It also makes it easy to manage versions of third-party libraries and ensures that your project always has the correct versions of the libraries it depends on.

Installing Composer

Before you can start using Composer, you'll need to install it on your system. Fortunately, Composer is very easy to install. You can visit our collection page regarding How To Install Composer. If you run into any issues during the installation process, the Composer documentation is a great resource for troubleshooting.

Once the installation is complete, you can verify that Composer is installed by running the following command:

composer --version

If Composer is installed correctly, you should see the version number printed in the terminal.

Checking Composer

Once you have Composer installed on your system, you can start using it to manage your project's dependencies.

To test your installation, run:

composer

Output:

   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 2.5.5 2023-03-21 11:50:05

Usage:
  command [options] [arguments]

Options:
  -h, --help                     Display help for the given command. When no command is given display help for the list command
  -q, --quiet                    Do not output any message
  -V, --version                  Display this application version
      --ansi|--no-ansi           Force (or disable --no-ansi) ANSI output
  -n, --no-interaction           Do not ask any interactive question
      --profile                  Display timing and memory usage information
      --no-plugins               Whether to disable plugins.
      --no-scripts               Skips the execution of all scripts defined in composer.json file.
  -d, --working-dir=WORKING-DIR  If specified, use the given directory as working directory.
      --no-cache                 Prevent use of the cache
  -v|vv|vvv, --verbose           Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  about                Shows a short information about Composer
  archive              Creates an archive of this composer package
  audit                Checks for security vulnerability advisories for installed packages
  browse               [home] Opens the package's repository URL or homepage in your browser
  bump                 Increases the lower limit of your composer.json requirements to the currently installed versions
  check-platform-reqs  Check that platform requirements are satisfied
  clear-cache          [clearcache|cc] Clears composer's internal package cache
  completion           Dump the shell completion script
  config               Sets config options
  create-project       Creates new project from a package into given directory
  depends              [why] Shows which packages cause the given package to be installed
  diagnose             Diagnoses the system to identify common errors
  dump-autoload        [dumpautoload] Dumps the autoloader
  exec                 Executes a vendored binary/script
  fund                 Discover how to help fund the maintenance of your dependencies
  global               Allows running commands in the global composer dir ($COMPOSER_HOME)
  help                 Display help for a command
  init                 Creates a basic composer.json file in current directory
  install              [i] Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json
  licenses             Shows information about licenses of dependencies
  list                 List commands
  outdated             Shows a list of installed packages that have updates available, including their latest version
  prohibits            [why-not] Shows which packages prevent the given package from being installed
  reinstall            Uninstalls and reinstalls the given package names
  remove               Removes a package from the require or require-dev
  require              [r] Adds required packages to your composer.json and installs them
  run-script           [run] Runs the scripts defined in composer.json
  search               Searches for packages
  self-update          [selfupdate] Updates composer.phar to the latest version
  show                 [info] Shows information about packages
  status               Shows a list of locally modified packages
  suggests             Shows package suggestions
  update               [u|upgrade] Updates your dependencies to the latest version according to composer.json, and updates the composer.lock file
  validate             Validates a composer.json and composer.lock

When a new Composer version is available, you can update your installation using the following command:

sudo composer self-update

Using Composer in a PHP Project

At this point, Composer is installed on your server. Now we will show you how to create a project with Composer.

First, create a new directory for your project and next, change the current directory to my-composer-project:

cd ~
mkdir my-composer-project
cd my-composer-project

Next, we can add packages using composer require command. To search for packages we can visit Packagist. In this example, we’ll use a PHP package called carbon to create a sample application that prints the current time. Run the following command to initialize a new Composer project and install the carbon package:

composer require nesbot/carbon

The above command will download and install carbon with all required dependencies and creates the composer.json file:

./composer.json has been created
Running composer update nesbot/carbon
Loading composer repositories with package information
Updating dependencies
Lock file operations: 5 installs, 0 updates, 0 removals
  - Locking nesbot/carbon (2.66.0)
  - Locking symfony/polyfill-mbstring (v1.27.0)
  - Locking symfony/polyfill-php80 (v1.27.0)
  - Locking symfony/translation (v6.2.8)
  - Locking symfony/translation-contracts (v3.2.1)
Writing lock file
Generating autoload files
5 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
No security vulnerability advisories found
Using version ^2.66 for nesbot/carbon

As shown in the output, Composer creates the composer.json file and downloads and installs carbon and all its dependencies.

If you list your project’s directory, you will see that it contains two files composer.json and composer.lock, and a vendor directory.

ls -l
// Output
-rw-r--r--@ 1 rexposed  staff     60 Apr 30 00:30 composer.json
-rw-r--r--@ 1 rexposed  staff  16644 Apr 30 00:30 composer.lock
drwxr-xr-x@ 7 rexposed  staff    224 Apr 30 00:30 vendor
  • vendor is the directory where the project dependencies are stored.
  • composer.lock is a file that keeps information about all installed packages and their versions, locking the project to the specific versions.
  • composer.json is the file that describes your PHP project, including the PHP dependencies and other metadata.

Note: All PHP packages installable with Composer are listed at Packagist.

Composer has autoload capabilities which allow us to use PHP classes without the need to require or include the files.

Create a file named test.php and add the following code:

<?php

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

use Carbon\Carbon;

printf("Now: %s", Carbon::now());

Let’s analyze the code line by line.

The vendor/autoload.php file is automatically generated by Composer and autoload all of the libraries.

Next line creates alias Carbon and the last line prints the current time using the Carbon now method.

Run the script by typing:

php test.php

The output should look something like this:

Now: 2023-04-29 18:48:44

Later, if you need to update the project packages, enter:

composer update

The command above will check for newer versions of the installed packages, and if a newer version is found and the version constraint match with the one specified in the composer.json, Composer will update the package.

Conclusion

Composer is a powerful tool for managing dependencies in your PHP projects. With this guide, you should have everything you need to get started with Composer.

Remember to refer to the official Composer documentation for more detailed information and troubleshooting tips.

About the Author

Rexposed Staff

Was this helpful?