从依赖项打印的Laravel Artisan命令输出



我正在编写一个自定义的artisan命令,它有一个服务作为依赖项:

class InstallCommand extends Command
{
protected $signature = 'mycommand:install';
/** @var InstallService */
private $installService;
public function __construct(InstallService $installService)
{
parent::__construct();
$this->installService = $installService;
}
public function handle()
{
$this->installService->install();
}
}

InstallService::install方法打印一些日志,在这种情况下,我希望将输出作为命令输出进行处理。

我发现的解决方案如下:

class InstallService
{
/** @var Command */
private $cmd;
public function setCommand(Command $cmd)
{
$this->cmd = $cmd;
}
public function install() {
$logText = "Some log";
if($this->cmd != null){
$this->cmd->info($logText);
} else {
Log::debug($logText);
}
}
}

在命令构造函数中:

class InstallCommand extends Command
{
public function __construct(InstallService $installService)
{
parent::__construct();
$installService->setCommand($this);
$this->installService = $installService;
}

有没有一种方法可以检测触发者是否是服务中独立的手工命令,然后避免使用InstallService::setCommand方法?

一旦检测到,我希望输出的样式与$this->info()命令打印的样式相同。例如,是否可以检索命令实例并调用相同的方法?

您可以使用https://laravel.com/api/9.x/Illuminate/Foundation/Application.html运行InConsole((方法

应用程序::运行InConsole((

if(App::runningInConsole())
{
//implicitly set command
}

更新:

信息使用write打印(str消息,bool换行(所以在命令内部使用write方法。

$this->output->write('this is the output', false);

最新更新