Laravel 5.4 中控制台外部命令的彩色输出

Vas*_*nko 2 php laravel laravel-5 laravel-5.4

在我可以输出的命令中

$this->error();
$this->info();
Run Code Online (Sandbox Code Playgroud)

但是如果我在 Command 中实例化其他类 - 我如何将彩色输出输出到该外部类中的控制台?其他类不扩展 Command 类。

我只找到了这个解决方案,我不喜欢它:)

<?php

use Illuminate\Console\Command;

class External
{
    /** @var Command */
    protected $command;

    public function __construct(Command $command) {
        $this->command = $command;
    }

    protected function error($msg)
    {
        $this->command->error($msg);
    }

    protected function info($msg, $v = null)
    {
        $this->command->info($msg, $v);
    }
}
Run Code Online (Sandbox Code Playgroud)

who*_*boy 7

您现有的方法似乎很合理。

您可以使用这种更轻松的方法。

  /*
    Black 0;30
    Blue 0;34
    Green 0;32
    Cyan 0;36
    Red 0;31
    Purple 0;35
    Brown 0;33
    Light Gray 0;37 
    Dark Gray 1;30
    Light Blue 1;34
    Light Green 1;32
    Light Cyan 1;36
    Light Red 1;31
    Light Purple 1;35
    Yellow 1;33
    White 1;37
  */

  echo "\033[31m some colored text \033[0m some white text \n";
  echo "\033[32m some colored text \033[0m some white text \n";
Run Code Online (Sandbox Code Playgroud)

您还可以访问底层 SymfonyCommand,因此在您现有的方法中您可以这样做

  <?php

  use Illuminate\Console\Command;
  use Symfony\Component\Console\Formatter\OutputFormatterStyle;

  class External
  {
      /** @var Command */
      protected $command;

      public function __construct(Command $command) {
          $this->command = $command;
      }

      protected function error($msg)
      {
          $this->command->error($msg);
      }

      protected function info($msg, $v = null)
      {
          $this->command->info($msg, $v);
      }
      protected function fire($msg)
      {
          // Custom colors
          $style = new OutputFormatterStyle('red', 'yellow', array('bold', 'blink'));
          $this->command->output->getFormatter()->setStyle('fire', $style);

          $this->command->output->writeln('<fire>' . msg . '</fire>');
      }
  }
Run Code Online (Sandbox Code Playgroud)


yog*_*g_a 5

第一种方法是在nunomaduro/collision包中实现的:

<?php

$color = new NunoMaduro\Collision\ConsoleColor;

echo($color->apply("red", "some text in red"));
Run Code Online (Sandbox Code Playgroud)