【问题标题】:Coloured Output To Console Outside Commands in Laravel 5.4Laravel 5.4 中控制台外部命令的彩色输出
【发布时间】:2017-03-25 15:47:06
【问题描述】:

里面的命令我可以输出

$this->error();
$this->info();

但是如果我在 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);
    }
}

【问题讨论】:

  • “你不喜欢它”是什么意思?它有效吗?如果是这样,那么问题是什么?
  • @maiorano84,工作量太大。耐用的解决方案。我从命令中实例化了 10 个类 - 我必须将命令注入所有这些类以及所有日志记录函数。
  • @maiorano84,这只是两个日志级别——还有更多!每个类都应该有额外的方法。

标签: php laravel laravel-5 laravel-5.4


【解决方案1】:

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

您可以使用更轻的this approach

  /*
    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";

您还可以访问底层的 SymfonyCommand,因此在您现有的方法中,您可以do this

  <?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>');
      }
  }

【讨论】:

【解决方案2】:

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

<?php

$color = new NunoMaduro\Collision\ConsoleColor;

echo($color->apply("red", "some text in red"));

【讨论】:

  • 只是用它来为我的播种机添加一点天赋 :) 只有第二个 arg 中的文本受到影响,因此您可以在之后使用默认控制台颜色在同一行上回显其他内容。
【解决方案3】:

您的命令是应用程序的入口点,而不是服务。它应该处理输入和输出。您的服务应该是隔离的,不要将它们耦合到控制台。

例如,如果您需要将应用程序更改为以不同的方式工作 - 而不是输出到控制台,它必须写入数据库。或者,它应该返回带有聚合消息的 JSON,而不是通过 CLI 运行。您将不得不更改您的每一项服务。

我要做的是在命令中注入服务,而不是相反。然后,让命令处理所有带有漂亮颜色的输出。

【讨论】:

    猜你喜欢
    • 2012-06-26
    • 1970-01-01
    • 2016-09-15
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 2018-07-01
    • 2014-12-13
    相关资源
    最近更新 更多