Класс SymfonyStyle
Класс SymfonyStyle - это обёртка над InputInterface и OutputInterface, которая упрощает создание красиво оформленного вывода в консольных командах. Он предоставляет методы для вывода заголовков, секций, текста, списков, таблиц, прогресс-баров, а также для интерактивного взаимодействия с пользователем (запросы, подтверждения, выбор).
Объект SymfonyStyle создаётся путём передачи входного и выходного потоков в конструктор. После этого его можно использовать в методе execute контроллера команды для формирования ответа.
Синтаксис
use Symfony\Component\Console\Style\SymfonyStyle;
$io = new SymfonyStyle($input, $output);
Пример
Давайте создадим простую команду, которая выводит приветствие с использованием основных методов оформления:
<?php
namespace App\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'app:greet',
description: 'Greets the user',
)]
class GreetCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->title('Greeting Command');
$io->text('Hello, user!');
$io->success('Command executed successfully.');
return Command::SUCCESS;
}
}
?>
Результат выполнения команды php bin/console app:greet:
Greeting Command
================
Hello, user!
[OK] Command executed successfully.
Пример
Давайте используем метод ask для запроса имени пользователя и метод confirm для подтверждения действия:
<?php
namespace App\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'app:interactive',
description: 'Interactive command example',
)]
class InteractiveCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$name = $io->ask('What is your name?', 'user');
$confirmed = $io->confirm('Are you sure?', false);
if ($confirmed) {
$io->success('Hello, ' . $name . '!');
} else {
$io->warning('Action cancelled.');
}
return Command::SUCCESS;
}
}
?>
Результат выполнения команды php bin/console app:interactive:
What is your name? [user]:
> abcde
Are you sure? (yes/no) [no]:
> yes
[OK] Hello, abcde!
Пример
Давайте создадим таблицу с данными с помощью метода table:
<?php
namespace App\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'app:table',
description: 'Displays a table',
)]
class TableCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$rows = [
['Article 1', 'Text 1', 100],
['Article 2', 'Text 2', 200],
['Article 3', 'Text 3', 300],
];
$io->table(
['Title', 'Description', 'Views'],
$rows
);
return Command::SUCCESS;
}
}
?>
Результат выполнения команды php bin/console app:table:
+-----------+-------------+-------+
| Title | Description | Views |
+-----------+-------------+-------+
| Article 1 | Text 1 | 100 |
| Article 2 | Text 2 | 200 |
| Article 3 | Text 3 | 300 |
+-----------+-------------+-------+