简体   繁体   English

Laravel Artisan 命令 output 从依赖项打印

[英]Laravel Artisan command output printed from a dependency

I'm writing a custom artisan command who has a service as dependency:我正在编写一个自定义工匠命令,该命令将服务作为依赖项:

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();
    }
}

The InstallService::install method prints some logs and I would like in this case the output to be handled as the command output. InstallService::install方法会打印一些日志,在这种情况下,我希望将 output 作为命令 output 处理。

The solution I found is as follows:我找到的解决方案如下:

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);
       }
    }
}

And in the command constructor:在命令构造函数中:

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

Is there a way to detect if the triggerer is an artisan command independently within the service and then avoid the need to have the InstallService::setCommand method?有没有办法检测触发器是否是服务中独立的工匠命令,然后避免需要InstallService::setCommand方法?

Once detected I want the output to be styled in the same way as that printed by the command with $this->info() .一旦检测到,我希望 output 的样式与$this->info()命令打印的样式相同。 Is it possible, for example, to retrieve the command instance and call the same method?例如,是否有可能检索命令实例并调用相同的方法?

You can do a check with https://laravel.com/api/9.x/Illuminate/Foundation/Application.html runningInConsole() method您可以使用https://laravel.com/api/9.x/Illuminate/Foundation/Application.html runningInConsole() 方法进行检查

App::runningInConsole()应用程序::runningInConsole()

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

Update:更新:

info prints using write(str message,bool newline) so inside the command use write method. info 使用 write(str message,bool newline) 打印,因此在命令内部使用 write 方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM