【问题标题】:Laravel, call many artisan commands with progress bar outputLaravel,使用进度条输出调用许多工匠命令
【发布时间】:2020-06-28 12:46:07
【问题描述】:

我创建了一个简单的特征来在命令执行期间生成一个进度条。

    <?php

    namespace App\Console\Commands;

    trait ProgressBarOutput
    {
        public function runProcess(\Countable $countable, callable $callback)
        {
            $bar = $this->output->createProgressBar(count($countable));
            $bar->start();
            foreach ($countable as $item) {
                call_user_func($callback, $item);
                $bar->advance();
            }
            $bar->finish();
            $this->line('');
        }
    }

这行得通,在我的命令页面中:

<?php

namespace App\Console\Commands;

use App\Console\Commands\ProgressBarOutput;
use Illuminate\Console\Command;

class MigrateUsers extends Command
{
    use ProgressBarOutput;

    protected $signature = 'migrate:users';
    protected $description = 'Migrate users table from old to new';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info("users");
        $rows = \DB::connection('old')->table('users')->get();
        $this->runProcess($rows, function($row) {
            \DB::connection('mysql')->table('users')->insert([
                'id' => $row->id,
                'name' => $row->name,
                'surname' => $row->surname,
            ]);
        });

        $this->info("cars");
        $rows = \DB::connection('old')->table('cars')->get();
        $this->runProcess($rows, function($row) {
            \DB::connection('mysql')->table('cars')->insert([
                'id' => $row->id,
                'model' => $row->model,
            ]);
        });
    }
}    

当我尝试将这些微导入拆分为单独的文件然后合并在一起时会出现问题:

public function handle()
{
    \Artisan::call("migrate:users");
    \Artisan::call("migrate:cars");
}

命令被正确调用,但没有打印输出,也没有进度条。 你有遇到过这样的问题吗?

谢谢!

【问题讨论】:

    标签: laravel laravel-artisan


    【解决方案1】:

    migrate 命令需要用户确认进程才能继续。在调用中添加--no-interaction 将删除所有用户交互。在这个例子中,它会像,

    public function handle()
    {
        \Artisan::call("migrate:users --no-interaction");
        \Artisan::call("migrate:cars --no-interaction");
    }
    

    【讨论】:

    • 它不起作用。我写“迁移”是因为我正在从一个数据库迁移到另一个数据库,但我可以称它为“app:users”。在任何情况下,进度条都会在流程完成后立即打印,而不是在执行期间打印。
    • 另外,如果我将“migrate:users”作为单个命令调用,进度条会逐渐正确地填充。如果我运行包含所有命令的“migrate:all”,进度条只会在最后打印。
    【解决方案2】:

    我解决了这个问题。

    只需调用 $this->call("your-command");而不是 \Artisan::call("your-command");

    public function handle()
    {
        $this->call("migrate:users");
        $this->call("migrate:cars");
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-10
      • 2016-04-07
      • 1970-01-01
      • 2014-08-30
      • 2020-02-05
      • 2018-06-24
      • 2021-09-15
      • 2013-09-25
      • 2015-09-24
      相关资源
      最近更新 更多