使用表格 来在命令行内显示表格化内容是 Console组件 中最受欢迎的功能之一。在 Symfony 4.2 中我们通过显示标题以及设置其最大行宽,对它进行了改进。

对表格添加标题

Contributed by
Dany Maillard
in #26933.

在 Symfony 4.2 中,使用 setHeaderTitle()setFooterTitle() 方法,表格可以在内容的上部和底部显示一个标题,对于复杂的或分页的表格来说,这十分理想:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
use Symfony\Component\Console\Helper\Table;
 // ...
 
$table = new Table($output);
$table
    ->setHeaderTitle('Books')
    ->setFooterTitle('Page 1/2')
    ->setHeaders(['ISBN', 'Title', 'Author'])
    ->setRows([
        ['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'],
        // ...
    ])
;
$table->render();

在你的终端里上例看起来像:

1
2
3
4
5
6
7
8
+---------------+----------- Books --------+------------------+
| ISBN          | Title                    | Author           |
+---------------+--------------------------+------------------+
| 99921-58-10-7 | Divine Comedy            | Dante Alighieri  |
| 9971-5-0210-0 | A Tale of Two Cities     | Charles Dickens  |
| 960-425-059-0 | The Lord of the Rings    | J. R. R. Tolkien |
| 80-902734-1-6 | And Then There Were None | Agatha Christie  |
+---------------+--------- Page 1/2 -------+------------------+

设置列的最大宽度

Contributed by
Roland Franssen
in #28373.

通过 setColumnWidth() 方法定义的列宽,应是列的最小宽度。若内容无法适应,列宽将扩为最大内容宽度。在 Symfony 4.2 中我们添加了一个全新的 setColumnMaxWidth() 方法,来把超长内容打包到一个可定义的列宽之中。

1
2
3
4
5
6
7
8
9
// ...
 
// the first argument is the column position (starting from 0) and
// the second argument is the max length in characters
// 第一个参数,是列的位置(从0起)
// 第二个参数,是以字符计的最大宽度
$table->setColumnMaxWidth(0, 5);
$table->setColumnMaxWidth(1, 10);
$table->render();

本例设置了第一例的最大宽度为5个字符,第二列的宽度为10个字符。给定内容将不再强塞到那些列中,而是被转换为多行:

1
2
3
4
5
6
7
8
+-------+------------+--------------------------------+
| ISBN  | Title      | Author                         |
+-------+------------+--------------------------------+
| 99921 | Divine Com | Dante Alighieri                |
| -58-1 | edy        |                                |
| 0-7   |            |                                |
|                (the rest of rows...)                |
+-------+------------+--------------------------------+