添加 composer.json 文件
在开发自定义模块时,有一些场景要求开发人员在模块中添加 composer.json 文件。其中一些场景取决于自定义模块是否打算作为一个项目提交到 drupal.org 社区。
如果模块开发者想要使用托管在 packagist.org 上的 PHP 库,他们必须在项目中添加 composer.json 文件。
如果模块是 drupal.org 上发布的模块,它依赖于其他模块,并且想要在开发过程中使用 DrupalCI 测试这些依赖的更改,那么它必须有一个 composer.json 文件来声明这些 Drupal 模块的依赖关系。(DrupalCI 只能检测 composer.json 中补丁的依赖更改,而不能检测 .info 或 .info.yml 文件中的更改。)
如果模块开发者希望使用 composer.json 提供的更灵活的版本约束(例如插入符号或波浪号运算符),这些功能只能在 composer.json 中实现。(虽然 Drupal 本身不会受这些约束影响,但如果最终用户使用 Composer 构建他们的网站,这些约束会在构建过程中被遵守。)
如果模块没有任何依赖,或者依赖仅限于其他 Drupal 模块,则不需要 composer.json 文件。然而,存在 composer.json 文件也不会产生负面影响。
无论开发者是否有 composer.json 文件,Drupal 模块的依赖关系仍然必须在其 .info.yml 文件中声明,以确保 Drupal 能够启用正确的模块。
将你的模块定义为一个 PHP 包
更广泛的 PHP 社区使用 Composer 管理包;Drupal 也采用了这种方式。例如,Drupal 项目依赖于 “drupal/core” 包。包类型 “drupal/core” 被定义为 “drupal-core”,因此 Composer 知道如何处理它。composer/installers 库定义了几个 Drupal 类型:
- drupal-module
- drupal-theme
- drupal-library
- drupal-profile
- drupal-drush
以下是 mobile_detect 项目如何使用 composer.json 依赖外部项目 mobiledetect/mobiledetectlib 的完整示例:
{ "name": "drupal/mobile_detect", "description": "Mobile_Detect is a lightweight PHP class for detecting mobile devices.", "type": "drupal-module", "homepage": "https://drupal.org/project/mobile_detect", "authors": [ { "name": "Matthew Donadio (mpdonadio)", "homepage": "https://www.drupal.org/u/mpdonadio", "role": "Maintainer" }, { "name": "Darryl Norris (darol100)", "email": "admin@darrylnorris.com", "homepage": "https://www.drupal.org/u/darol100", "role": "Co-maintainer" } ], "support": { "issues": "https://drupal.org/project/issues/mobile_detect", "irc": "irc://irc.freenode.org/drupal-contribute", "source": "https://cgit.drupalcode.org/mobile_detect" }, "license": "GPL-2.0-or-later", "minimum-stability": "dev", "require": { "mobiledetect/mobiledetectlib": "~2.8" } }
在为你的包命名时,你必须遵循 Drupal Composer 命名约定。
在 composer.json 中定义依赖
如果需要,你可以在 composer.json 中定义模块的外部依赖。Drupal 核心不会自动检测或管理这些依赖。 要使用项目 composer.json 文件中定义的依赖,你必须使用以下其中一种方式:
有关 composer 作为 Drupal 依赖管理器的更多信息,请查看 Composer 与 Drush Make 的比较。
添加对其他 Drupal 模块的依赖
默认情况下,Composer 在解析依赖时只会查看 Packagist 上的包。大多数 Drupal 模块不会发布到那里,因为 Drupal 有自己的仓库。因此,你可能会看到类似以下的错误信息:
请求的包 drupal/module 在任何版本中都未找到,可能是包名拼写错误。
你可以通过运行以下命令告诉 Composer 在 packages.drupal.org 仓库中查找 Drupal 模块:
$ composer config repositories.drupal composer https://packages.drupal.org/8
该命令会在你的 composer.json 文件中添加如下部分:
"repositories": { "drupal": { "type": "composer", "url": "https://packages.drupal.org/8" } }
Drupal 9 兼容性
拥有 composer.json 文件不是 Drupal 9 兼容性的必需条件。Drupal 9 兼容性 由 info.yml 文件决定。如果你的项目包含 composer.json 文件,那么是否包含 drupal/core 版本约束也不是 Drupal 9 兼容性的必需条件。然而,如果你的 require 部分声明了 drupal/core 的版本要求,那么它必须与 Drupal 9 兼容。