Команда make:command
Команда make:command создаёт новый класс консольной команды в директории src/Command. Первым параметром передаётся имя класса команды. Команда доступна только при установленном пакете symfony/maker-bundle.
Синтаксис
php bin/console make:command <name>
Пример
Давайте создадим команду с именем AppSendMessageCommand:
php bin/console make:command AppSendMessageCommand
В результате будет создан файл команды:
<?php
namespace AppCommand;
use SymfonyComponentConsoleAttributeAsCommand;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
#[AsCommand(
name: 'app:send-message',
description: 'Add a short description for your command',
)]
class AppSendMessageCommand extends Command
{
protected function configure(): void
{
$this
->addArgument('arg1', InputArgument::OPTIONAL, 'Argument description')
->addOption('option1', null, InputOption::VALUE_NONE, 'Option description')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$arg1 = $input->getArgument('arg1');
if ($arg1) {
$io->note(sprintf('You passed an argument: %s', $arg1));
}
if ($input->getOption('option1')) {
// ...
}
$io->success('You have a new command! Now make it your own! Pass --help to see your options.');
return Command::SUCCESS;
}
}
?>
Запустим созданную команду:
php bin/console app:send-message hello
Результат выполнения команды:
[OK] You have a new command! Now make it your own! Pass --help to see your options.
Пример
Давайте изменим команду и добавим вывод переданного аргумента:
<?php
namespace AppCommand;
use SymfonyComponentConsoleAttributeAsCommand;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
use SymfonyComponentConsoleStyleSymfonyStyle;
#[AsCommand(
name: 'app:send-message',
description: 'Send a message to the user',
)]
class AppSendMessageCommand extends Command
{
protected function configure(): void
{
$this->addArgument('message', InputArgument::REQUIRED, 'Message text');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$message = $input->getArgument('message');
$io->success($message);
return Command::SUCCESS;
}
}
?>
Запустим команду с текстом 'hello':
php bin/console app:send-message hello
Результат выполнения команды:
[OK] hello
Смотрите также
-
атрибут
AsCommand,
который задаёт имя и описание команды -
параметр
name,
который задаёт имя консольной команды -
параметр
description,
который задаёт описание консольной команды -
параметр
aliases,
который задаёт псевдонимы консольной команды