Метод interact класса Command
Метод interact класса Command вызывается перед методом execute и служит для организации интерактивного диалога с пользователем. В этот метод передаются объекты InputInterface и OutputInterface, через которые можно задавать вопросы и получать ответы. Метод не возвращает значение, а лишь подготавливает входные данные для основного выполнения команды.
Синтаксис
protected function interact(InputInterface $input, OutputInterface $output): void
Пример
Давайте создадим команду, которая запрашивает у пользователя имя и выводит его:
<?php
namespace AppCommand;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
use SymfonyComponentConsoleQuestionQuestion;
class HelloCommand extends Command
{
protected static $defaultName = 'app:hello';
protected function configure(): void
{
$this->setDescription('Greets the user');
}
protected function interact(InputInterface $input, OutputInterface $output): void
{
$question = new Question('Please enter your name: ', 'guest');
$name = $this->getHelper('question')->ask($input, $output, $question);
$input->setArgument('name', $name);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$name = $input->getArgument('name');
$output->writeln('Hello, ' . $name . '!');
return Command::SUCCESS;
}
}
?>
Результат выполнения команды в терминале:
Please enter your name: abcde
Hello, abcde!
Пример
Давайте запросим у пользователя подтверждение перед выполнением опасного действия:
<?php
namespace AppCommand;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
use SymfonyComponentConsoleQuestionConfirmationQuestion;
class DeleteCommand extends Command
{
protected static $defaultName = 'app:delete';
protected function configure(): void
{
$this->setDescription('Deletes an article');
}
protected function interact(InputInterface $input, OutputInterface $output): void
{
$question = new ConfirmationQuestion('Are you sure? (y/n) ', false);
$confirmed = $this->getHelper('question')->ask($input, $output, $question);
$input->setOption('force', $confirmed);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
if (!$input->getOption('force')) {
$output->writeln('Operation cancelled.');
return Command::FAILURE;
}
$output->writeln('Article deleted.');
return Command::SUCCESS;
}
}
?>
Результат выполнения команды при отказе:
Are you sure? (y/n) n
Operation cancelled.
Смотрите также
-
класс
Command,
который представляет консольную команду -
метод
execute,
который выполняет основную логику команды -
метод
configure,
который настраивает аргументы и опции команды -
метод
initialize,
который вызывается перед interact