【发布时间】:2017-10-31 09:33:07
【问题描述】:
将控制台输出记录器添加到从工匠命令类调用的服务类中的最佳做法是什么。
示例代码:
<?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 颜色)。
【问题讨论】:
标签: php laravel console phpunit laravel-artisan