Метод initialize класса Command
Метод initialize класса Command
вызывается автоматически перед методом execute
при запуске консольной команды. Он принимает два
параметра: InputInterface - объект ввода
и OutputInterface - объект вывода. Метод
позволяет выполнить предварительную настройку
ввода и вывода до начала основной логики команды.
Он не возвращает значение и не должен содержать
основную бизнес-логику.
Синтаксис
protected function initialize(InputInterface $input, OutputInterface $output): void
Пример
Давайте создадим команду, в которой метод
initialize выводит сообщение о начале
выполнения:
<?php
namespace AppCommand;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
class ArticleCommand extends Command
{
protected static $defaultName = 'app:article';
protected function initialize(InputInterface $input, OutputInterface $output): void
{
$output->writeln('initialization');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln('execution');
return Command::SUCCESS;
}
}
?>
Результат выполнения команды:
php bin/console app:article
initialization
execution
Пример
Давайте в методе initialize установим
значение аргумента по умолчанию, если он не передан:
<?php
namespace AppCommand;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
class ArticleCommand extends Command
{
protected static $defaultName = 'app:article';
protected function configure(): void
{
$this->addArgument('name', InputArgument::OPTIONAL, 'Article name');
}
protected function initialize(InputInterface $input, OutputInterface $output): void
{
if (!$input->getArgument('name')) {
$input->setArgument('name', 'abcde');
}
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$name = $input->getArgument('name');
$output->writeln($name);
return Command::SUCCESS;
}
}
?>
Результат выполнения команды без аргумента:
php bin/console app:article
"abcde"