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?
My Answer:
> installService = $installService; } public function handle() { $this->info('Starting installation process...'); $this->installService->install(); $this->info('Installation completed successfully.'); }}
In this example, the `InstallCommand` class has a dependency on the `InstallService` class. The `InstallService` class is injected into the `InstallCommand` class through the constructor. When the `handle` method of the `InstallCommand` class is called, it first prints a message indicating that the installation process is starting. It then calls the `install` method of the `InstallService` class to perform the installation process. Finally, it prints a message indicating that the installation process has been completed successfully.
Rate this post
4 of 5 based on 8276 votesComments