如何从命令本身调用Laravel命令句柄?

时间:2018-03-28 07:51:13

标签: php laravel artisan

我有这样的命令

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

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

TestCommand也在Kernel.php注册。

现在我需要扩展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();

现在我需要调用ExtendedCommand我可以用它做什么?没有在kernel.php中注册此命令的解决方案会更好,因为我不是在寻找Artisan::call方式。

1 个答案:

答案 0 :(得分:1)

更像这样

<?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
    }
}