Creating Custom Commands¶
Drush commands are plain Symfony Console commands, run by Drupal's dr. A module provides a command by adding a class; there is no Drush base class, and no Drush-specific registration. See Drush 15: The Doctor will see you now
Where commands live¶
Put each command in its own class under the module's src/Command directory:
- File:
modules/custom/example/src/Command/XkcdFetchCommand.php - Namespace:
Drupal\example\Command
Drupal finds every class in that directory that has an #[AsCommand] attribute, registers it as a service, and autowires its constructor. The module must be installed, and the container rebuilt (dr cc container) after you add a command.
Writing a command¶
<?php
declare(strict_types=1);
namespace Drupal\example\Command;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use GuzzleHttp\ClientInterface;
use Symfony\Component\Console\Attribute\Argument;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Output\OutputInterface;
/**
* An example console command.
*
* Drupal discovers classes with #[AsCommand] in a module's src/Command
* directory and autowires their constructor arguments. To try this one, copy it
* to modules/example/src/Command/XkcdFetchCommand.php in a module named
* 'example', enable the module, then run `dr xkcd random`.
*/
#[AsCommand(
name: self::NAME,
description: 'Display a link to an xkcd cartoon.',
aliases: ['xkcd'],
usages: [
'123',
'random',
],
)]
final class XkcdFetchCommand
{
use StringTranslationTrait;
public const string NAME = 'xkcd:fetch';
public function __construct(
private readonly ClientInterface $httpClient,
) {
}
public function __invoke(
OutputInterface $output,
#[Argument('A cartoon number, or "random". If omitted, the latest cartoon is used.')]
string $search = '',
): int {
$url = match (true) {
$search === '' => 'https://xkcd.com',
ctype_digit($search) => 'https://xkcd.com/' . $search,
$search === 'random' => 'https://xkcd.com/' . random_int(1, $this->latestNumber()),
default => throw new \InvalidArgumentException((string) $this->t('@search is not a cartoon number or "random".', ['@search' => $search])),
};
$output->writeln($url);
return Command::SUCCESS;
}
/**
* Returns the number of the most recent cartoon.
*/
private function latestNumber(): int
{
$response = $this->httpClient->request('GET', 'https://xkcd.com/info.0.json');
$info = json_decode((string) $response->getBody(), true, flags: JSON_THROW_ON_ERROR);
return (int) $info['num'];
}
}
The pieces:
- The class is invokable: it has an
__invoke()method and extends nothing. By convention its name ends inCommand, and it declarespublic const string NAMEholding the command name. #[AsCommand]declares the name,description,aliases,usages,help, andhidden. Usages are shown after the command name, so write'123', not'xkcd 123'.- Arguments and options are
__invoke()parameters marked#[Argument]or#[Option]. The parameter type sets the input mode: a parameter with a default is optional,boolis a flag, andarrayaccepts many values. UsesuggestedValuesfor shell completion. Ask forInputInterfaceorOutputInterfaceas parameters when you need them. - Return
Command::SUCCESSorCommand::FAILURE, or an integer exit code. Throw an exception to report an error; Console prints it and exits non-zero. - User-facing strings go through
StringTranslationTrait:(string) $this->t('Deleted @name.', ['@name' => $name]).
Dependency injection¶
Type-hint services in the constructor. Where a type hint is ambiguous, name the service with Symfony's #[Autowire(service: 'config.storage')] on the parameter. See Dependency Injection.
Prompting for input¶
Mark an argument with #[Ask('Which queue?')] to prompt when it is missing. For anything more involved, such as autocompletion, add a method marked #[Interact]. It runs before __invoke(), and only when the command is interactive:
#[Interact]
public function askForName(InputInterface $input, OutputInterface $output): void
{
if (empty($input->getArgument('config_name'))) {
$question = new Question((string) $this->t('Choose a configuration'));
$question->setAutocompleterValues($this->configFactory->listAll());
$input->setArgument('config_name', (new SymfonyStyle($input, $output))->askQuestion($question));
}
}
Altering other commands¶
Listen to Console's events to act before or after another command runs. See Event Subscribers.
Testing¶
Write a kernel test that builds the command, drives it with Symfony's CommandTester, and asserts on getDisplay() and the exit code. See QueueTest.
Upgrading from Drush 13¶
In addition to the table below, see the drupal.org docs.
| Drush 13 | Now |
|---|---|
src/Drush/Commands/FooCommands.php, one method per command |
src/Command/FooCommand.php, one class per command |
extends DrushCommands or extends Command |
An invokable class with no base class |
#[CLI\Command], @command |
#[AsCommand] |
#[CLI\Argument], #[CLI\Option], configure() |
#[Argument], #[Option] on __invoke() |
#[CLI\Usage] |
usages: on #[AsCommand] |
Interact hook, interact() |
#[Interact] method or #[Ask] |
| Validate hooks, validation Attributes | Validate inside __invoke() and throw |
RowsOfFields, FormatterTrait |
OutputFormat option, render output yourself |
dt() |
$this->t() |
$this->logger(), $this->io() |
Inject LoggerInterface; use SymfonyStyle |
AutowireTrait, create(), drush.services.yml |
Constructor autowiring by Drupal's container |
Site-wide and global commandfiles, --include |
Commands live in modules |