skillberto / command-handler
简单的独立命令处理库。
v1.2
2016-10-07 20:17 UTC
Requires
- symfony/console: ~2.3
- symfony/process: ~2.3
Requires (Dev)
- phpunit/phpunit: ~4
This package is not auto-updated.
Last update: 2024-09-20 22:03:32 UTC
README
安装
通过 composer 安装
$ composer require skillberto/command-handler "~1.0"
作者和贡献者
- Norbert Heiszler(创建者,开发者)
用法
以下示例展示了如何使用它
use Symfony\Component\Console\Output\ConsoleOutput;
use Skillberto\CommandHandler\CommandHandler;
use Skillberto\CommandHandler\Command;
$output = new ConsoleOutput();
$handler = new CommandHandler($output);
$handler->add( 'some commands' );
... or
$handler->addCommand(new Command('some commands'));
$handler->execute();
您还可以定义集合
$handler->addCollection(array('some commands'));
... or
$handler->addCommands(array(new Command('some commands')));
如果您想跳过不必要的命令
$handler->addSkippable('some commands');
... or
$handler->addCommand(new Command('some commands', false));
... or add more commands
$handler->addSkippableCollection( array( 'some commands' ) );
... or
$handler->addCommands(array(new Command('some commands', false)));
$handler->execute();
...之后您可以得到以下命令
$handler->getSkippedMessages();
但是,如果您不跳过命令,并且它没有成功执行
$handler->getErrorMessage();
高级用法
前缀
以下示例展示了如何使用前缀
...
$handler = new CommandHandler($output, "php ");
... or
$handler = new CommandHandler($output);
$handler->addPrefix("php ");
... then
$handler->add("--version");
$handler->execute();
在这种情况下,您将执行 php --version。
超时
可以为每个命令定义,也可以只为某些命令定义,或者两者都定义。
$handler = new CommandHandler($output, "", 0.2);
... or
$handler = new CommandHandler($output);
$handler->setTimeout(0.2);
... then
$handler->addCommand(new Command("php --version", true, 0.3);
$handler->add('something');
$handler->execute();
在之前的示例中,每个命令都将有 "0.2 秒" 的执行时间,除了 php --version,它有 "0.3 秒"。
让我们看看如何定义组超时
$handler = new CommandHandler($output);
$handler->setTimeout(0.2);
$handler->addCollection(array('some command'));
$handler->setTimeout(0.3);
$handler->addCollection(array('some command'));
$handler->execute();
在这个例子中,第一个集合有 "0.2 秒",第二个 "0.3 秒"。
处理程序注入,合并
在某些情况下,我们需要定义多个处理程序,例如:对于不同的前缀。但不用担心,我们有有用的方法
$handler_1->addHandler($handler_2);
这是好的,但前缀和超时怎么办?对于这些问题,CommandHandler 有三种不同的合并类型: MERGE_ALL, MERGE_NON, MERGE_NOT_DEFINED 默认是 MERGE_NON,但您可以更改它
$handler_1->addHandler($handler_2, CommandHandler::MERGE_ALL, CommandHandler::MERGE_NOT_DEFINED);
在之前的例子中,前缀合并有 MERGE_ALL 类型,超时有 MERGE_NOT_DEFINED 类型。 MERGE_ALL 表示 $handler_1 的前缀 / 超时将用于所有这些。 MERGE_NOT_DEFINED 表示如果 $handler_2 命令没有定义,则使用 $handler_1 的前缀 / 超时。 MERGE_NON 表示前缀和超时将被分开。
回调
您可以为每次执行定义一个回调
...
use Symfony\Component\Process\Process;
use Skillberto\CommandHandler\Command;
...
$handler->execute(function(Progress $progress, Command $command) {
//something more
});