PHP Composer

From HaFrWiki42
Jump to navigation Jump to search

Composer is a tool for dependency management in PHP. [1][2]  It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
Composer is an application-level package manager for PHP. It is inspired by NodeJs's NPM and Ruby's Bundler, and is currently the recognized package manager by the community.
The Composer ecosystem consists of two parts:

  • the Composer, which is the command-line utility for installing packages,
  • the Packagist, the default package repository.

Install Composer

At the moment of writing (last update May 2021) the latest version of Composer is 2.0.13.
To install Composer:

In the end you may check where composer is installed. My installation:

$ which composer
composer is /usr/local/bin/composer

$ composer --version
Composer version 2.0.13 2021-04-27 13:11:08

Tutorial Remarks

Install faker:

$ mkdir /Users/Shared/Sources/Tutorials/Composer 
$ cd /Users/Shared/Sources/Tutorials/Composer
$ composer require fzaninotto/faker

Under the hood, Composer downloads the zip file of Faker from Github. Besides downloading the required package, Composer will also create some internal files. The structure look like:

Composer
-rw-r--r--  1 xxxx  yyyy    62B May 15 12:09 composer.json
-rw-r--r--  1 xxxx  yyyy   2.1K May 15 12:09 composer.lock
drwxr-xr-x  5 xxxx  yyyy   160B May 15 12:09 vendor
   -rw-r--r--   1 xxxx  yyyy   178B May 15 12:09 autoload.php
   drwxr-xr-x  10 xxxx  yyyy   320B May 15 12:09 composer
        -rw-r--r--  1 xxxx  yyyy    13K May 15 12:09 ClassLoader.php
        -rw-r--r--  1 xxxx  yyyy   1.0K May 15 12:09 LICENSE
        -rw-r--r--  1 xxxx  yyyy   147B May 15 12:09 autoload_classmap.php
        -rw-r--r--  1 xxxx  yyyy   149B May 15 12:09 autoload_namespaces.php
        -rw-r--r--  1 xxxx  yyyy   211B May 15 12:09 autoload_psr4.php
        -rw-r--r--  1 xxxx  yyyy   1.7K May 15 12:09 autoload_real.php
        -rw-r--r--  1 xxxx  yyyy   830B May 15 12:09 autoload_static.php
        -rw-r--r--  1 xxxx  yyyy   1.5K May 15 12:09 installed.json
   drwxr-xr-x   3 xxxx  yyyy    96B May 15 12:09 fzaninotto
        drwxr-xr-x  9 xxxx  yyyy   288B May 15 12:09 faker
        ...

composer.json

This file describes the dependencies of your project. It is a simple JSON file and shows you what packages are installed in your project.

  • Whenever you run composer require from command line, composer.json and composer.lock will be automatically updated to reflect package change.
  • Conversely, if you add a package to composer.json file, you run composer install to download the new package.
  • If you want to update all packages' versions to the latest specified by their version constraints, you can run composer update.

composer require

This command is used to add an individual package to the dependencies. Whenever we need a new package, we can just run it. It is convenient because we do not have to touch the composer.json file at all.
Another usage of this command is to update an existing package's version. For example, we have installed the latest version(1.4.0) of Faker using composer require fzaninotto/faker as Composer fetchesthe latest version of a package if we do not specify its version constraint. Since our application is incompatible with 1.4.0, we need to install 1.2.0 in order to run composer require fzaninotto/faker:1.2 0. It will download a specific package and update all relevant Composer files accordingly.

composer install

This command first looks for composer.lock file,

  • if it is present, exact version of the packages defined, will be installed and composer.son will then be ignored.
  • If it is not present, the command will check packages defined in the composer.json file and download the latest versions of the packages that match the supplied version constraints.

Can you spot the difference? When composer.lock is used, exact versions are downloaded, whereas using composer.json, Composer will always attempt to retrieve the latest version of a package that matches the supplied version constraint.
When version constraint is defined as an exact number, both actions have the same result. However this is rarely the case.
This command is used when we begin a new project - we define a list of dependencies and run this command to get all packages installed. Or, when kick-start someone else's project, we check out their code from Github and run this command to get all dependencies installed.
In some deployment strategies, we run this command in production to install the application after pulling its source code from repository.

composer update

This command only reads from composer.json file which is different from composer install. It updates existing packages to the latest versions that match supplied version constraints defined in composer.json. Meanwhile, it downloads any new packages added to composer.json file.
We can use this command to update existing packages' versions, similar to composer require. The difference is that composer require does not require us to touch the composer.json file manually, it feels more intuitive.
The fact that this command only reads from composer.json brings up a common pitfall, which is running this on production. We should never run composer update in production.
Here's why:

  • If your application is working well with Faker 1.2.0 on your local development environment, you push your code to production and run composer update.
  • Without your knowledge, the latest version of Faker has already been updated to 1.4.0, so Composer downloads version 1.4.0 of Faker in production, because you have defined its version constraint as 'fzaninotto/faker: 1.*' in composer.json.
  • As a result, your production is now using a different package from your development. This is not the intended outcome.

We recommend deploying composer.lock along with compose.json and running composer install in production. This will ensure your production has the same packages as your development.


composer.lock

While composer.json file lets us define packages we need using versions constraints, composer.lock tracks exact versions of packages installed in our project. In other words, it stores the current state of our project. This is a very important point to remember.
The fact that composer install reads first from composer.lock, makes it a much safer command to use.
Here's why:

  • If you delete vendor completely from the project, this will remove all packages Composer downloaded.
    Now run composer install again and it will obtain the exact versions of packages as it previously did.


This brings up our next point. If we are using a version control system such as Git, should we commit composer.lock?
The answer is "It Depends".

  • Most of time we want to make sure everyone is sharing identical source code at anytime. So we will commit composer.lock. This is very common since most of us work with a team.
  • The rare case of not committing composer.lock is when we develop a package(library), because users rarely need to run composer install in our package.


Composer gives us a lot of flexibility in using its commands, however there are a couple of rules we try to follow to prevent liability.

  • composer install is our friend - use it in production for deployment.

Location installed Programs

A very important question is: Where are my installed programs?.
Answer: in your composer sub-directory vendor/bin.

Workflow

A fair standard Composer workflow:

  • install: Defined some dependencies in composer.json: run composer install
    • The install command reads the composer.lock file from the current directory, processes it, and downloads and installs all the libraries and dependencies outlined in that file.
      If the file does not exist it will look for composer.json and do the same.
  • require: Need an individual package: run composer require some/package
    • The require command adds required packages to your composer.json and installs them.
      • If you do not specify a package, composer will prompt you to search for a package, and given results, provide a list of matches to require.
      • If you do not specify a version constraint, composer will choose a suitable one based on the available package versions.
      • If you do not want to install the new dependencies immediately you can call it with --no-update
  • update: Need multiple packages: define them in composer.json file and run composer update
  • require..:new-version: Want to test out one single newly released package: run composer require some/package:new-version
  • update: Ready to test out all the latest versions of packages released: run composer update

Useful command-line

$ composer --help
Usage:
  help [options] [--] [<command_name>]

Arguments:
  command                        The command to execute
  command_name                   The command name [default: "help"]

Options:
      --xml                      To output help as XML
      --format=FORMAT            The output format (txt, xml, json, or md) [default: "txt"]
      --raw                      To output raw command help
  -h, --help                     Display this help message
  -q, --quiet                    Do not output any message
  -V, --version                  Display this application version
      --ansi                     Force ANSI output
      --no-ansi                  Disable ANSI output
  -n, --no-interaction           Do not ask any interactive question
      --profile                  Display timing and memory usage information
      --no-plugins               Whether to disable plugins.
  -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

Help:
  The help command displays help for a given command:
  
    php /usr/local/bin/composer help list
  
  You can also output the help in other formats by using the --format option:
  
    php /usr/local/bin/composer help --format=xml list
  
  To display the list of available commands, please use the list command.

Available commands:

  about                Shows the short information about Composer.
  archive              Creates an archive of this composer package.
  browse               Opens the package's repository URL or homepage in your browser.
  cc                   Clears composer's internal package cache.
  check-platform-reqs  Check that platform requirements are satisfied.
  clear-cache          Clears composer's internal package cache.
  clearcache           Clears composer's internal package cache.
  config               Sets config options.
  create-project       Creates new project from a package into given directory.
  depends              Shows which packages cause the given package to be installed.
  diagnose             Diagnoses the system to identify common errors.
  dump-autoload        Dumps the autoloader.
  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                 Displays help for a command
  home                 Opens the package's repository URL or homepage in your browser.
  i                    Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json.
  info                 Shows information about packages.
  init                 Creates a basic composer.json file in current directory.
  install              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                 Lists commands
  outdated             Shows a list of installed packages that have updates available, including their latest version.
  prohibits            Shows which packages prevent the given package from being installed.
  remove               Removes a package from the require or require-dev.
  require              Adds required packages to your composer.json and installs them.
  run                  Runs the scripts defined in composer.json.
  run-script           Runs the scripts defined in composer.json.
  search               Searches for packages.
  self-update          Updates composer.phar to the latest version.
  selfupdate           Updates composer.phar to the latest version.
  show                 Shows information about packages.
  status               Shows a list of locally modified packages.
  suggests             Shows package suggestions.
  u                    Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file.
  update               Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file.
  upgrade              Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file.
  validate             Validates a composer.json and composer.lock.
  why                  Shows which packages cause the given package to be installed.
  why-not              Shows which packages prevent the given package from being installed.

See also

top

Internal

External

Tutorial

  • Star Tutorial, Modern PHP Developer Composer.
    Creates the test composer project fzaninotto/faker. See the directory /Users/Shared/Sources/Tutorials/Composer.
  • w3resource, Create, Publish and Use your first composer package.
  • w3resource, How to update composer packages with webhooks.php.

Reference

top

  1. GetComposer, documentation.
  2. Composer, English Wikipedia