Writing Drush 9 Commands

Drupal Camp LA 2019 - Ashok Modi

About Presenter

  • Using Drupal for long enough
    • Was years before I realized Drush is the fucking bomb
  • CLI commands are the best

What is Drush?

  • Interact with Drupal from a Terminal
    • includes hundreds of commands
    • Clear caches
      • drush cr
    • Dump database
      • drush sql:dump
    • Set up site
      • drush site:setup
    • and more with your own custom commands!

Why Drush?

  • Mature
  • Built on Symfony Console
  • Fairly easy to understand

What about Drupal Console?

  • Still good
  • Still works
  • Other option for Drupal
  • Much closer to symfony console
    • One command per class

What do you need?

  • composer.json
  • drush.services.yml
  • src/Commands/ModuleCommands.php
    • Name this whatever you want

composer.json

{
    "name": "org/my_module",
    "description": "This extension provides new commands for Drush.",
    "type": "drupal-drush",
    "authors": [
        {
            "name": "Author name",
            "email": "author@example.com"
        }
    ],
    "require": {
        "php": ">=5.6.0"
    },
    "extra": {
        "drush": {
            "services": {
                "drush.services.yml": "^9"
            }
        }
    }
}

drush.services.yml

services:
  swlaw_colleague.commands:
    class: \Drupal\swlaw_colleague\Commands\ModuleCommands
    tags:
      - { name: drush.command }

ModuleCommands will map to whatever you name your file

ModuleCommands.php

  • This is your class
  • Will have annotations to get discovered
    • Multiple commands in one file
    • Specify command name
<?php

namespace Drupal\my_module\Commands

class ModuleCommands extends DrushCommands {

  /**
   * @command mymodule:command1
   * @aliases mym:c1
   */
  public function myFirstCommand() {
    // ...
  }
}

Annotations

  • @command
    • The command
  • @alias
    • The alias
  • @option
    • Your option(s).
  • @param
    • Your argument. Required.

Logger

  • Use with $this->logger()
    • $this->logger()->success('yay!');
    • $this->logger()->alert('shit');

Input/Output

  • $this->io()->...
    • ask
    • choice
    • confirm
    • etc.

Hands-on time

Note to self

  • Remember to enable dcla2019 module :)

Questions?

Thank you