Nuevo en Symfony 4.4: Tablas horizontales y listas de definición en comandos de consola

El componente Console incluye algunas funcionalidades para crear tablas y configurarlas de maneras muy diferentes. En Symfony 4.4 lo hemos mejorado con nuevos tipos de tablas.

Tablas horizontales

Observa la siguiente tabla creada en un comando de consola de Symfony:

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
// ...
 
class SomeCommand extends Command
{
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $table = new Table($output);
        $table
            ->setHeaders(['ISBN', 'Title', 'Author'])
            ->setRows([
                ['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'],
            ])
        ;
        $table->render();
    }
}

El resultado de ejecutar este código es el siguiente:

+---------------+--------------------------+------------------+
| 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  |
+---------------+--------------------------+------------------+

Si añades una llamada al nuevo método setHorizontal(bool $horizontal = true), la tabla se transforma en una "tabla horizontal", donde la información se muestra en filas en vez de en columnas:

$table
    ->setHeaders(['ISBN', 'Title', 'Author'])
    ->setRows([
        // ... las filas de datos ...
    ])
    ->setHorizontal()
;
+--------+-----------------+----------------------+-----------------------+--------------------------+
| ISBN   | 99921-58-10-7   | 9971-5-0210-0        | 960-425-059-0         | 80-902734-1-6            |
| Title  | Divine Comedy   | A Tale of Two Cities | The Lord of the Rings | And Then There Were None |
| Author | Dante Alighieri | Charles Dickens      | J. R. R. Tolkien      | Agatha Christie          |
+--------+-----------------+----------------------+-----------------------+--------------------------+

Si utilizas el estilo Symfony para comandos de consola, puedes usar directamente el atajo horizontalTable():

use Symfony\Component\Console\Style\SymfonyStyle;
 
protected function execute(InputInterface $input, OutputInterface $output)
{
    $io = new SymfonyStyle($input, $output);
    $io->horizontalTable(
        ['ISBN', 'Title', 'Author'],
        [
            // ... the rows ...
        ]
    );
}

Listas de definición

En Symfony 4.4 también hemos añadido soporte para crear "listas de definición", que son una serie de pares clave-valor similar al elemento <dl> de HTML. Las listas de Symfony son más flexibles porque permiten incluir títulos, separadores, etc.

use Symfony\Component\Console\Helper\TableSeparator;
 
$io->definitionList(
    ['Version' => '4.4.0'],
    ['Long-Term Support' => 'Yes'],
    new TableSeparator(),
    'Timeline',
    ['End of maintenance' => '11/2022'],
    ['End of life' => '11/2023']
);

Este ejemplo se muestra por pantalla de la siguiente forma:

-------------------- ---------
 Version              4.4.0
 Long-Term Support    Yes
-------------------- ---------
 TIMELINE
 End of maintenance   11/2022
 End of life          11/2023
-------------------- ---------

Esta funcionalidad fue contribuida por Grégoire Pineau en el pull request #32742.

Fuente: New in Symfony 4.4: Horizontal Tables and Definition Lists in Console Commands

Comentarios

Publicada el

23 de octubre de 2019

Etiquetas

Proyectos Symfony destacados

La forma más sencilla de generar el backend de tus aplicaciones Symfony. Ver más

Síguenos en @symfony_es para acceder a las últimas noticias.