当我在终端php artisan migrate
中运行时,如果没有任何迁移,则会导致“无法迁移”。
当我在代码中使用Artisan::call('migrate')
(在自定义Artisan命令中使用它)时,这不会返回任何消息。它只是执行代码而没有任何反馈。
如果我vardump()
Artisan::call
方法的结果它只返回一个int(0)
是否有可能得到Artisan调用方法的响应?
所有命令的返回结果在类Symfony\Component\Console\Command\Command
中定义,方法run
:
return is_numeric($statusCode) ? (int) $statusCode : 0;
$statusCode
变量是通过调用命令的execute
方法设置的,该方法在工匠的情况下在类Illuminate\Console\Command
中定义:
protected function execute(InputInterface $input, OutputInterface $output)
{
return $this->fire();
}
fire
方法的结果由单个命令决定,在php artisan migrate
命令的情况下,从方法返回任何内容,因此$statusCode
为null(这就是为什么你从Symfony\Component\Console\Command\Command::run
方法返回0)
如果你想从自定义命令中获得响应,只需从fire
方法返回一个整数,它将冒回到$statusCode
。您可以使用它以编程方式切换自定义命令的不同结果。
如果您特别想从artisan:migrate
命令获取结果,那么我认为除了在您自己调用它的自定义命令中包装命令之外,您还可以做很多事情来更改返回值。
对于使用Laravel 5.1的所有这些都没有用,但你可以简单地使用:
Artisan::output()
我能够通过以下方式获得Artisan :: call()的输出:
use Symfony\Component\Console\Output\StreamOutput;
$stream = fopen("php://output", "w");
Artisan::call("migrate", array(), new StreamOutput($stream));
var_dump($stream);
是的,这是可能的。要从自定义命令中获取内置artisan命令的输出,请将OutputStream
从命令传递到Artisan::call
。例:
class MyCommand extends \Illuminate\Console\Command
{
public function fire()
{
\Artisan::call('optimize', [], $this->getOutput());
}
}
迟到但可能对搜索用例的人有用。
让我添加我在测试中如何将结果打印到控制台。我的问题是在测试运行迁移时打印输出。我正在使用模块,并希望看到迁移过程的结果。
$this->artisan('module:migrate');
//same as running php artisan module:migrate or
// $this->app['Illuminate\Contracts\Console\Kernel']->call('module:migrate');
echo $this->app['Illuminate\Contracts\Console\Kernel']->output();
当您想要的Artisan命令输出时发出echo
。
您可以使用ob_start和ob_get_clean访问此类型的输出。
例如,如果你的命令是回声JSON。
Artisan::command('myecho:command', function () {
echo json_encode(config('myconfig'), true);
})->describe('outputs json');
然后,您可以通过将命令调用包装在缓冲区中来访问JSON输出:
\ob_start();
\Artisan::call('myecho:command');
$output = \ob_get_clean();
var_dump($output);