Shobi
Shobi

Reputation: 11461

How do I call a Laravel commands handle from the command itself?

I have a command like this

class TestCommand extends Command {
 .....
 constructor
 .....

 public function handle()
 {
    ....
    command logic
    ....
 }
}

the TestCommandis registered in the Kernel.php also.

now I need to extend TestCommand,

class ExtendedCommand extends TestCommand {

  public function __construct ()
  {
    parent::__constrct();
    .....
    modify some variables
    .....
  }

  public function sync()
  {
     //trying to call the parent class handle method.

     $this->handle(); // not working & getting PHP Error:  Call to a member function getOption() on null in /home/vagrant/sinbad/vendor/laravel/framework/src/Illuminate/Console/Command.php on line 292
     $this->execute(); // obviously not working & getting TypeError: Too few arguments to function Illuminate\Console\Command::execute(),
  }
}

//instantiating the new command
   new(ExtendedCommand)->sync();

Now I need to call the ExtendedCommand what are the possible ways I can do it? a solution without registering this command in the kernel.php would be better, cause I am not looking for an Artisan::call way.

Upvotes: 0

Views: 1844

Answers (1)

krisanalfa
krisanalfa

Reputation: 6438

More like this

<?php

class TestCommand extends Command
{
    public function __construct(Handler $handler)
    {
        parent::__construct();

        $this->handler = $handler;
    }

    public function handle()
    {
        $this->handler->handle();
    }
}

// No need to extends from TestCommand
class ExtendedCommand extends Command
{
    public function __construct(Handler $handler)
    {
        parent::__construct();

        $this->handler = $handler;

        // do the rest
    }

    public function sync()
    {
        $this->handler->handle();
        $this->execute();
    }
}

class Handler
{
    public function handle()
    {
        // Put your logic here
    }
}

Upvotes: 1

Related Questions