编写 Composer Installer 插件需实现 InstallerInterface 并注册为 composer-plugin 类型,在 extra.installer-types 中声明支持的自定义 type,通过 supports()、isInstalled()、install()、update() 四方法控制安装逻辑,并在 PluginInterface::activate() 中绑定安装器。

编写 Composer Installer 插件需要实现 ComposerInstallerInstallerInterface,并注册为 Composer 的自定义安装器类型。核心在于告诉 Composer:当遇到特定 type 的包时,用你的逻辑来决定安装路径、是否启用脚本、如何处理源码等。
Composer 通过 type 字段识别包类型(如 library、wordpress-plugin)。你写的插件需声明支持某个自定义 type(例如 my-framework-bundle),并在该类型包被安装/更新时介入。
type 必须是 composer-plugin
extra.installer-types 中显式声明你支持的自定义类型(否则 Composer 会忽略)你的安装器类必须实现四个核心方法:
supports():返回 true 当且仅当传入的 PackageInterface 的 getType() 匹配你支持的类型(如 my-app-extension)isInstalled():检查目标路径是否存在有效安装(通常判断 vendor/{vendor}/{name} 下是否有预期文件或标志)install():执行实际复制/软链/生成动作。使用 $io 输出提示,用 $filesystem 安全操作路径(推荐 copy() 或 relativeCopy())update():先调用 uninstall() 再调用 install(),或按需做增量更新(如只覆盖 changed 文件)注意:install() 和 update() 中不要硬编码 vendor/ 路径,应通过 $package->getInstallationSource() 和 $composer->getConfig()->get('vendor-dir') 动态获取。
在插件主类中,通过 PluginInterface::activate() 获取 InstallerEvents 并注册你的安装器实例:
$composer->getInstallationManager()->addInstaller($yourInstaller)
composer.json 的 autoload 中配置)composer.json 中设置:"extra": {"class": "Your\Plugin\MyInstallerPlugin"}
supports() 中用 in_array($package->getType(), $this->supportedTypes) 判断开发阶段避免反复 install/uninstall:
composer install --no-scripts --no-plugins 跳过插件,快速验证基础依赖$io->writeError('[DEBUG] ...') 输出调试信息(writeError 确保可见)"type": "my-custom-type",require 你的插件,运行 composer update 观察行为vendor/composer/installed.json 是否记录了你的包类型和安装路径不复杂但容易忽略:Composer 缓存可能使修改后的插件不生效,可临时加 --no-cache 或删 vendor/composer/installed.json 后重试。
以上就是如何编写一个自定义的Composer Installer插件?(高级开发)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号