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