2017-03-25 88 views
-2

內部命令之外的命令,我可以輸出彩色輸出到控制檯中Laravel 5.4

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

,但如果我實例化內部命令其他類 - 如何使彩色輸出到外部類中的安慰?其他類不擴展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); 
    } 
} 
+0

你是什麼意思,「你不喜歡它」?它工作嗎?如果是這樣,那麼問題是什麼? – maiorano84

+0

@ maiorano84,工作太多了。 durty解決方案。我從命令實例化了10個類 - 我必須將Command注入到它們全部以及所有日誌記錄功能中。 –

+0

@ maiorano84,這裏只有兩個日誌級別 - 其中有更多!並且每個人都應該在所有的課程中都有額外的方法。 –

回答

0

您現有的做法似乎相當合理。

您可以使用更輕的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>'); 
     } 
    }