Laravel Artisan 命令行:表格输出 1 个改进

问题

我能否在 Artisan 命令中以表格形式输出多行多列数据?

回答

我们可以在命令中使用 table 方法以表格形式输出数据。下面是一个 demo:table 闭包命令,它演示了 table 的用法:

Artisan::command('demo:table', function () {

    $headers = ['日期', '订单数', '备注'];

    $orders = [
        ['2019-05-20', '75'],
        ['2019-05-21', '80'],
        ['2019-05-22', '89'],
        ['2019-05-23', '91'],
        ['2019-05-24', '139', '促销']
    ];

    $this->table($headers, $orders);

})->describe('Demo table method');

只需传入表头和行数据给 table 方法,我们就可以获得美观的表格形式的数据输出。

效果:

表格输出

这是 table 方法的源码(vendor\laravel\framework\src\Illuminate\Console\Command.php):

    /**
     * Format input to textual table.
     *
     * @param  array   $headers
     * @param  \Illuminate\Contracts\Support\Arrayable|array  $rows
     * @param  string  $tableStyle
     * @param  array   $columnStyles
     * @return void
     */
    public function table($headers, $rows, $tableStyle = 'default', array $columnStyles = [])
    {
        $table = new Table($this->output);

        if ($rows instanceof Arrayable) {
            $rows = $rows->toArray();
        }

        $table->setHeaders((array) $headers)->setRows($rows)->setStyle($tableStyle);

        foreach ($columnStyles as $columnIndex => $columnStyle) {
            $table->setColumnStyle($columnIndex, $columnStyle);
        }

        $table->render();
    }

可以看到,table 方法还支持表格样式及各列数据样式的定义,我们修改下上面的 demo:table 命令,让用户在执行命令时可选择表格样式:

Artisan::command('demo:table', function () {

    $headers = ['日期', '订单数', '备注'];

    $orders = [
        ['2019-05-20', '75'],
        ['2019-05-21', '80'],
        ['2019-05-22', '89'],
        ['2019-05-23', '91'],
        ['2019-05-24', '139', '促销']
    ];

    $style = $this->choice(
        '请选择表格样式:', 
        ['default', 'borderless', 'compact', 'symfony-style-guide', 'box', 'box-double'], 
        0
    );

    $this->table($headers, $orders, $style);

})->describe('Demo table method');

效果:

表格输出

注意:boxbox-double 样式显示中文数据可能会有错位情况发生。

参考

本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!