2017-05-30 73 views
1

將控制檯輸出記錄程序添加到由artisan命令類調用的服務類的最佳做法是什麼?服務中的Laravel Artisan控制檯輸出,單元可測試

示例代碼:

<?php 
class Import extends Command 
{ 
    public function handle() 
    { 
      /** @var \Services\ServiceImport $service */ 
      $service = resolve($this->resolvers[$db]) 
       ->setCommand($this); 

      # Console output 
      $this->info(sprintf('Starting import for "%s"', $service::SERVICE_NAME)); 
      $imported = $service->import($this->argument('file')); 

      $this->info(sprintf('Total rows imported: %d', $imported)); 
     } 
    } 
} 

/** Different file, service from container */ 

class ServiceImport extends Service 
{ 
    protected $cmd; 

    public function import($file) 
    { 
     # Need this console output 
     $this->cmd->info(sprintf('Importing file "%s"', $file)); 
     // [...] More stuff goes on..this illustrates my point 
    } 

    public function setCommand(Command $cmd) 
    { 
     $this->cmd = $cmd; 
     return $this; 
    } 
} 

這工作,但沒有試圖單元測試ServiceImport時,因爲$cmd未設置......我還沒有想出一個辦法來模擬一個Command得到這個工作,要麼。我該如何做到這一點?

我敢肯定我錯過了什麼。這是我如何使用服務?在處理期間,我不能是唯一希望運行一個持續運行的詳細日誌的人。

使用Laravel 5.4,artisan命令。

我不想使用Log::作爲我特別寫入控制檯(具有良好的Symfony顏色)。

回答

1

由於您只想創建日誌輸出,您可以通過檢查null來解決此問題。

在服務剛注入命令依賴性與函數的參數如下所示:

public function import($file, Command $cmd = null) 
{ 
    # Need this console output 
    if($cmd != null) { 
     $this->cmd->info(sprintf('Importing file "%s"', $file)); 
    } 
    // [...] More stuff goes on..this illustrates my point 
} 

在您的測試,你可以很容易地忽略$cmd參數,因爲這不應該影響你的服務代碼。

如果過度使用這種類型的輸出,創建一個特質或一個基類中包含的功能:

public function info(string $message, Command $cmd = null) 
{ 
    if($cmd != null){ 
     $cmd->info($message); 
    } else { 
     //perhaps log message otherwise in test environment 
     // or when service is used outside of artisan commands 
    } 
} 

而且你可以在你的服務

$this->info(sprintf('Importing file "%s"', $file), $cmd); 
+0

是到處使用這個。你是對的。接近我發現的解決方案。我所做的是通過AbstractCommand類注入$ cmd,爲它覆蓋run()。我使用Partyline(https://statamic.com/blog/partyline)作爲一種方法,但是可以將一個完整的PSR記錄器添加到Monolog堆棧中。完美的作品。更多信息:https://redd.it/6j42h5 – guice

相關問題