在composer.json的extra字段中存储自定义数据是插件配置的常见做法,Composer本身不处理但允许第三方读取。通过$composer->getPackage()->getExtra()可在插件中获取配置,建议使用唯一键名如my-plugin-config避免冲突,支持嵌套结构并提供默认值确保健壮性。

在 composer.json 的 extra 字段中存储自定义数据,是一种常见做法,尤其适用于插件需要读取配置或元信息的场景。Composer 本身不会处理这些数据,但允许第三方工具或插件读取并使用它们。
extra 是一个对象字段,可以包含任意键值对。你可以直接在其中定义插件所需的配置。
例如:{ "name": "your/plugin", "type": "composer-plugin", "require": { "composer-plugin-api": "^2.0" }, "extra": { "my-plugin-config": { "enable-feature": true, "log-level": "debug", "supported-formats": ["json", "xml"] }, "author-notes": "This config is for internal use only." }, "autoload": { "psr-4": { "Your\Plugin\": "src/" } } }
在你的插件代码中,可以通过 Composer 的 PackageInterface 获取根项目的 extra 数据。
示例代码:
use ComposerComposer;
use ComposerIOIOInterface;
use ComposerPluginPluginInterface;
class MyPlugin implements PluginInterface
{
public function activate(Composer $composer, IOInterface $io)
{
$extra = $composer->getPackage()->getExtra();
if (isset($extra['my-plugin-config'])) {
$config = $extra['my-plugin-config'];
// 使用配置
if (!empty($config['enable-feature'])) {
$io->write('
}
}
}
}
为避免键名冲突,建议在 extra 中使用插件名称作为前缀或命名空间。
推荐方式:
以上就是如何在composer.json的extra部分为插件存储自定义数据?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号