How do I create a Drush command

Here is how I scaffold a module to be able to run Drush commands.

First, I create the module with Drupal Console: drupal generate:module

Then, I have to create the file drush_services.yml and include this in it:

services:
  MY_MODULE.commands:
  class: \Drupal\MY_MODULE\Commands\WHATEVERINAMEMYCLASSCommands
  tags:
    - { name: drush.command }

In the root of the module, create a folder called src (lowercase) and under that another folder called Commands. There create a file called WHATEVERINAMEMYCLASSCommands.php and include this code:

namespace Drupal\MY_MODULE\Commands;

use Consolidation\OutputFormatters\StructuredData\RowsOfFields;
use Drush\Commands\DrushCommands;

/**
* A Drush commandfile.
*
* In addition to this file, you need a drush.services.yml
* in root of your module, and a composer.json file that provides the name
* of the services file to use.
*
* See these files for an example of injecting Drupal services:
* - http://cgit.drupalcode.org/devel/tree/src/Commands/DevelCommands.php
* - http://cgit.drupalcode.org/devel/tree/drush.services.yml
*/
class WHATEVERINAMEMYCLASSCommands extends DrushCommands
{
  /**
  * Does some stuff that needs a Drush command
  *
  * @command MY_MODULE:display_warning
  * @aliases mm_display_warning
  * @usage MY_MODULE:display_warning
  * Displays a warning about the intruder Reynir is
  */
  public function displayWarning()
  {
    $this->logger()->warning("Reynir is an intruder");
  }
}

Then just install the module as usual. Go to console and run drush mm_display_warning

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.