一个Composer插件可在install或update后输出提示信息。需设置type为composer-plugin,实现PluginInterface接口,并通过EventSubscriberInterface监听post-install-cmd和post-update-cmd事件,在对应回调中执行逻辑。

想让 Composer 做更多事?你可以通过编写插件来扩展它的行为。Composer 插件允许你在 Composer 执行过程中注入自定义逻辑,比如在安装包时执行特定操作、修改依赖解析方式或添加新的命令。下面带你一步步了解如何创建一个基础的 Composer 插件。
Composer 在启动时会扫描已安装的包,查找标记为插件类型的包,并自动激活它们。插件通过监听 Composer 的事件(如 pre-install-cmd、post-update-dump 等)来运行代码。
要成为一个有效的插件,你的类必须实现 ComposerPluginPluginInterface 接口,并定义 activate() 方法,在其中注册事件监听器或绑定服务。
我们来创建一个插件,它会在每次执行 composer install 或 update 后打印一条提示信息。
新建一个目录,例如 my-composer-plugin,然后初始化 Composer 配置:
mkdir my-composer-plugin cd my-composer-plugin composer init
确保 composer.json 中包含以下内容:
{
"name": "your-vendor/my-composer-plugin",
"type": "composer-plugin",
"require": {
"composer-plugin-api": "^2.0",
"composer/composer": "^2.0"
},
"autoload": {
"psr-4": {
"MyPlugin\": "src/"
}
},
"extra": {
"class": "MyPlugin\HelloPlugin"
}
}创建目录 src/ 并添加文件 HelloPlugin.php:
<?php
namespace MyPlugin;
use ComposerComposer;
use ComposerIOIOInterface;
use ComposerPluginPluginInterface;
use ComposerEventDispatcherEventSubscriberInterface;
use ComposerScriptEvent;
use ComposerInstallerPackageEvent;
class HelloPlugin implements PluginInterface, EventSubscriberInterface
{
public function activate(Composer $composer, IOInterface $io)
{
// 插件激活时调用
}
public static function getSubscribedEvents()
{
return [
'post-install-cmd' => 'onPostInstall',
'post-update-cmd' => 'onPostUpdate',
];
}
public function onPostInstall(Event $event)
{
$event->getIO()->write('<info>Hello from your Composer plugin! ?</info>');
}
public function onPostUpdate(Event $event)
{
$event->getIO()->write('<info>Updated dependencies – custom plugin reporting in! ?</info>');
}
}getSubscribedEvents() 定义你要监听的事件及回调方法。$event->getIO()->write() 输出带格式的信息。在本地测试插件前,先在主项目中通过 repositories 引入它。
编辑你想要测试插件的项目的 composer.json:
"repositories": [
{
"type": "path",
"url": "../my-composer-plugin"
}
]运行命令安装你的插件:
composer require your-vendor/my-composer-plugin @dev
安装成功后,每次运行 composer install 或 update,都会看到插件输出的提示信息。
$io->writeError() 输出到错误流,便于排查。以上就是如何创建一个Composer插件来扩展其功能_Composer插件开发入门基础教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号