How to create a custom drush command for drupal 8 ?
To create a custom drush command, you must create a custom module like this (Here, mymodule).
Then add a file : YOUR_MODULE.drush.inc (Here mymodule.drush.inc)
Example :
<?php
/**
* Mymodule is a Test module, This is drush command example
* mymodule
*/
/**
* Implements hook_drush_command().
*/
function mymodule_drush_command() {
$commands = [];
$commands['my-cmd'] = [
'description' => 'A test command my-cmd.',
];
$commands['mycommand'] = [
'description' => 'This is my example command.',
'aliases' => ['mec'],
'arguments' => [
'arg1' => 'My custom argument 1.',
'arg2' => 'My custom argument 2.',
],
'options' => [
'opt1' => 'My custom option.',
],
'examples' => [
'drush mec' => 'Print my example command.',
'drush mec myargument' => 'Print my example command with an argument "myargument".',
'drush mec myargument --opt1=myoption' => 'Print my example command with an argument "myargument" and an option "myoption".',
],
];
return $commands;
}
/**
* Call back function drush_custom_drush_command_say_hello()
* The call back function name in the following format
* drush_{module_name}_{item_id_for_command}()
*/
function drush_mymodule_my_cmd() {
// Your codes
return "My Drush command 'my-cmd' is OK";
}
/**
* Test command 2 : mycommand or mec
*/
function drush_mymodule_mycommand($arg = '?') {
// Your codes
$opt1 = drush_get_option('opt1', 'N/A');
drush_print("Argument : $arg, Option : $opt1");
return "My Drush command 'mycommand' is OK";
}
Print Error, Warning, Success or OK message
drush_log('Test Success message','success');
drush_log('Test Warning message','warning');
drush_log('Test Error message','error');
drush_log('Test OK message','ok');
drush_log('Test Cancel message','cancel');
Run a drush command (Print help command).
drush_invoke('help', ['cex']);
User input - Prompt for user input in Drush
Ask for options
$options = [
'Test' => t('Test'),
'0' => t('Error'),
];
$option = drush_choice($options, t('Please choose a option.'));
Ask Yes/No Confirmation
NOTE : If you set the option -y
, this will return TRUE
without prompting.
if (drush_confirm('Are you sure you want printed \'Hello world\' to the screen ?')) {
drush_print('Hello world !!!');
}
else {
drush_user_abort();
}
Ask for input value
$value = drush_prompt(dt('Please enter your name'));
drush_print(dt('Hello @value!', ['@value' => $value]));
Note : The procedure is same as on Drupal 7
Tips
To get arguments, you can also use:
$args = func_get_args();
Comments