【问题标题】:Custom Artisan Command to execute multiple commands自定义 Artisan 命令以执行多个命令
【发布时间】:2020-09-04 10:09:13
【问题描述】:

有没有办法执行一些工匠命令,使用自定义工匠命令,就像我想制作一个名为的自定义命令:

$ php artisan project:init 

它将执行一些命令,例如php artisan migrate:refreshphp artisan db:seedphp artisan config:clear

有什么办法吗?

【问题讨论】:

  • 您好,您能接受我的回答吗?

标签: php laravel laravel-artisan


【解决方案1】:

是的,您可以通过编程方式调用控制台命令

https://laravel.com/docs/7.x/artisan#programmatically-executing-commands https://laravel.com/docs/7.x/artisan#calling-commands-from-other-commands

我曾多次使用它来将命令捆绑在一起。例如:

$this->call('custom:command1', [
    '--argument1' => 'foo',
]);

$this->call('custom:command2', [
    '--argument1' => 'bar',
]);

【讨论】:

  • 很高兴我能帮上忙 :)
【解决方案2】:

有两种方法可以对命令进行分组或从另一个命令调用它。

变体 1: 在 routes/console.php 中创建新的控制台命令。 routes/console.php

Artisan::command('project:init', function () {
    Artisan::call('migrate:refresh', []); // optional arguments
    Artisan::call('db:seed');
    Artisan::call('config:clear');
})->describe('Running commands');

变体 2: 根据文档:https://laravel.com/docs/7.x/artisan#calling-commands-from-other-commands

使用命令行创建新命令:

$ php artisan make:command ProjectInit --command project:init

这将创建新文件:App\Console\Commands\ProjectInit

ProjectInit 类的 handle 方法中,您可以调用其他命令:

public function handle(){
  $this->call('migrate:refresh', []); // optional arguments
  $this->call('db:seed');
  $this->call('config:clear');
}

【讨论】:

  • 谢谢,我已经通过阅读您提到的文档来发出命令,并且在我按照文档中提到的laravel.com/docs/7.x/… 调用这些命令后,它就起作用了
  • 很高兴为您提供帮助,请接受此答案以结束问题。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 2021-08-11
  • 2015-08-29
  • 2016-04-06
  • 2016-04-05
  • 1970-01-01
相关资源
最近更新 更多