从一个Artisan命令返回另一个命令

时间:2017-08-25 13:40:39

标签: php laravel

我试图从另一个命令调用一个Artisan(Laravel)命令。但是,我需要能够从“main”命令调用的命令中检索数组...

// Command 1
public function handle() {
    $returnedValue = $this->call( 'test:command' );

    dump( $returnedValue ); // <-- is 5

}

// Command 2
public function handle() {
    return $this->returnValue();

}

private function returnValue() {
    $val = 5;
    return $val;
}

我查看过文档并找不到办法,所以我想知道是否有办法,或者我是否需要重新考虑我的方法。

谢谢!

1 个答案:

答案 0 :(得分:1)

Artisan Commands的行为与例如Controller函数的行为方式不同。他们返回exitCode,在我的测试中总是0(如果抛出错误,则无法返回任何内容)。

如果您尝试获取返回值,您的方法将无法正常工作,但您可以访问\Artisan::output();以查看您调用的第一个artisan命令究竟发送了什么。

// FirstCommand.php
public function handle(){
  \Artisan::call("second:command");
  if(\Artisan::output() == 1){
    $this->info("This Worked");
  } else {
    $this->error("This Didn't Work");
  }
}

注意:我使用\Artisan::call();在使用$this->call()没有按预期工作的情况下,两者之间存在一些明显的差异,但\Artisan::call()确实存在差异。无论正在执行的代码是什么,$this->call()都会向01发送回来;不确定那里有什么。在Laravel 5.0上测试过,它远远落后于当前,所以也许就是它。

// SecondCommand.php
public function handle(){
  try {
    $test = 1 / 1;
  } catch (\Exception $ex){
    $this->error("0");
  }

  $this->info("1");
}

在我的控制台中运行php artisan first:command会返回:

  

$ php artisan first:command

     

这个工作

现在,如果将$test中的代码切换为

$test = 1 / 0;

我在我的控制台中得到了这个:

  

$ php artisan first:command

     

这个没有工作

所以,我想这里的规则是避免在你要用\Artisan::output()检查的结果之前输出第二个命令中的任何内容。

相关问题