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.
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?
Once detected I want the output to be styled in the same way as that printed by the command with $this->info(). Is it possible, for example, to retrieve the command instance and call the same method?