Symfony:如何自定义可用命令的输出?

时间:2015-06-30 20:25:35

标签: symfony symfony-2.7 symfony-console

我们正在使用 symfony / console 构建一个控制台应用程序(顺便说一下,很棒的库)。可用的命令显示如下:

Available commands:
  check-deps     Get a report of resolved and missing (if any) dependencies.
  gen-docs       Rebuild the API / code documentation
  help           Displays help for a command
  list           Lists commands
  restart        Restart the Nginx and PHP-FPM processes.
  show-changes   Show all local changes to the source code since the last push.
  test           Run the unit tests
  test-coverage  Run the unit tests and include a coverage report.

该命令的名称以绿色显示,描述显示为白色。

目前,可用命令是唯一的部分。有没有一种简单的方法使用OOP为命令创建多个部分

或者,有没有办法更改命令标签的绿色颜色?

1 个答案:

答案 0 :(得分:2)

您可以使用冒号表示法创建新部分。

$this
        ->setName('newSection:greet') //<--- This line does the trick
        ->setDescription('Greet someone')
        ->addArgument(
            'name',
            InputArgument::OPTIONAL,
            'Who do you want to greet?'
        )
        ->addOption(
           'yell',
           null,
           InputOption::VALUE_NONE,
           'If set, the task will yell in uppercase letters'
        );

但是在这种情况下,您需要运行您的命令,并将新的部分名称添加为命名空间, > php app.php newSection:greet Avindra

如果你用“New Section”这样的空格命名你的部分,你需要调用你的命令,比如 > php app.php "New Section:greet" Avindra

这就是你可以改变应用程序本身info注释的颜色的方法。

#!/usr/bin/env php
<?php
require __DIR__.'/vendor/autoload.php';

use Command\GreetCommand;
use Command\HelloCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;

$application = new Application();
$application->add(new GreetCommand());
$application->add(new HelloCommand());

//Create a new OutputFormatter
$formatter = new OutputFormatter();
//Change info annotation color by blue
$formatter->setStyle('info', new OutputFormatterStyle('blue'));
//Construct output interface with new formatter
$output = new ConsoleOutput(OutputInterface::VERBOSITY_NORMAL, null, $formatter);

//Run your application with your new output interface
$application->run(null, $output);

您可以在此处查看相关的源代码以获取更多选项; https://github.com/symfony/Console/blob/5f241906889f0a3e7b1854b42e7c92a0ea8516ce/Formatter/OutputFormatter.php#L51

https://github.com/symfony/Console/blob/b6b351d326e2fb2fe673a808630f938c2881a473/Formatter/OutputFormatterStyle.php#L21

希望它有所帮助。