在 Ubuntu 系统中,要为 Composer 自定义命令,你需要遵循以下步骤:
-
创建一个新的 PHP 文件,例如
my-custom-command.php,并将其放在一个合适的位置,例如项目的根目录或全局 Composer 插件目录。 -
在
my-custom-command.php文件中,编写你的自定义命令类。这个类需要继承Symfony\Component\Console\Command\Command类,并实现configure()和execute()方法。例如:
#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class MyCustomCommand extends Command
{
protected function configure()
{
$this
->setName('my:custom-command')
->setDescription('A custom Composer command')
->setHelp('This command does something special...');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// 在这里编写你的命令逻辑
$output->writeln('Hello, this is my custom command!');
}
}
- 使你的自定义命令文件可执行:
chmod +x my-custom-command.php
- 如果你想将自定义命令全局可用,将其移动到 Composer 的全局插件目录。你可以通过运行以下命令找到该目录:
composer global config home
将 my-custom-command.php 文件移动到该目录下的 vendor/bin 文件夹中。
- 确保全局插件目录在你的系统路径中。你可以通过将以下内容添加到你的
~/.bashrc或~/.bash_profile文件中来实现:
export PATH="$PATH:$HOME/.composer/vendor/bin"
然后运行 source ~/.bashrc 或 source ~/.bash_profile 使更改生效。
- 现在你可以在终端中使用你的自定义命令:
my:custom-command
这将执行你在 MyCustomCommand 类中定义的命令逻辑。