All of the modules, themes, and distributions hosted on Drupal.org are made available as Composer packages. You can use Composer to download and update these packages for your Drupal application.
First, ensure that your application follows Acquia’s best practices as defined in How to structure your Drupal repository. At minimum, your composer.json file must:
- Include the
drupal key in the repositories array so that Composer is able to locate the Drupal packages hosted on Drupal.org
- Have a properly configured installer-paths key in order to ensure that Drupal projects are downloaded to the correct directories in your local repository
Composer and Drush use the same words to mean different things. Notably, the word "install" means one thing in Composer parlance and something very different in Drupal parlance.
|Terminology||Composer Meaning||Drupal & Drush Meaning|
|Install||Download to local repository and make available via Composer Autoloader||Install to Drupal database|
|Package||A Composer package, inclusive of Drupal modules, themes, distros, etc.||A group of modules listed on the Drupal admin "Extend" page.|
|Project||A type of package.||A module, theme, distro, or other repository hosted on Drupal.org.|
Composer allows you to "require" a set of dependencies that it "installs." Again, in Composer parlance, “install” simply means that the Composer package will be downloaded and correctly loaded (made available to PHP classes) by the Composer autoloader.
To use Composer to "install" a new Drupal project (module, theme, profile, etc.), execute:
composer require drupal/[project-name]
[project-name] is the machine name of the project (module, theme, distro, etc.) on Drupal.org. You can always find the machine name of a Drupal project on it’s project page on Drupal.org:
For instance, to require token, execute:
composer require drupal/token
This will add
drupal/token to the
require array in your
composer.json. It will choose a default version constraint based on your
composer.json configuration. E.g., if you have specified
"prefer-stable": "true" then this will download the latest stable version of the package.
You may also specify the version constraint by adding second argument:
composer require drupal/token ^1.1.0
Make sure to commit the changes to
composer.lock after requiring the new module. As mentioned above and in How to Structure Your Drupal Repository, the Drupal module files will not be committed to Git. Rather, Composer will read the contents of
composer.lock when installing or deploying your site to another environment in order to install the expected packages.