Custom Drush commands

Ready for review -- AWAITING PEER REVIEW
Description: 
Create your own drush commands in PHP
Overview: 

When you create your own modules or functionalities, it is important to create also your own drush commands.You would learn how to write PHP code and to transform it in a drush command.

Prerequisites: 

PHP, Drush,Drupal

Steps: 

Suppose that you have a module called "example" and you want to create a new drush command for your module.

  1. Step 1: Create a file command file called example.drush.inc
  2. Step 2: Implement the function example_drush_command()
    Implement the function example_drush_command() in your example.drush.inc file.
    This function returns all your drush commands that are implemented in your new module.

    function example_drush_command() {
      $commands['hello_world'] = array(
        'description' => 'Say Hello World when it is called',
        'examples' => array(
          'drush hello_world' => 'Say Hello World at prompt'
          ),
        'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_FULL,
        'aliases' => array('hw','helwor')
        );

      $commands['say_name'] = array(
        'description' => 'Say your address when it is called',
        'examples' => array(
            'drush say_name --name=Drupal' => 'Say Hello Drupal at prompt'
            ),
        'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_FULL,
        'aliases' => array('sn'),
        'options' => array(
            'name' => 'Your name'
            )
        );
      return $commands;
    }

  3. Step 3: Implement the functions that will be called by your commands.
    Every command that was specified in your example_drush_command() function should have a callback function that will be invoked.

    Callback function for drush hello_world command can be:

    function drush_example_hello_world() {
      echo 'Hello World';
    }

    Callback function for drush say_name command can be:

    function drush_example_say_name() {
      $name = drush_get_option('name','Unknown User');
      echo sprintf("Hello %s" . PHP_EOL,$name);
    }

  4. Now, you can run the following commands:
    drush hello_world
    drush hw
    drush helwor
    drush say_name --name=Drupal
    drush sn --name=Drupal

Lesson tags: