Drupal: How to Create Your Own Drush Command

Posted by Unknown on Monday, May 26, 2014

Drush is a command line tool built to assist you in working with Drupal from the terminal. It comes by default with a bunch of useful commands, such as downloading, enabling or even updating modules. But modules can define their own commands to have Drush perform operations using their code.


In this article we are going to look at creating a Drush command for a fictitious module that really doesn’t do anything. The purpose is to illustrate what you need to do on the Drush side of things and not have to worry about the actual functionality of the module that defines the command. If you want to follow along, I assume that you already have your own custom module set up. Doesn’t matter what it does.


All the code we write is available in this repository so if you want to follow along or even skip ahead, you can check it out. Each commit represents a different step we take in the tutorial.


Our module


The demo_drush module functionality we want to expose to Drush will be super simple. It’s a function that sets the Hello world! message:



function demo_drush_print_statement() {
drupal_set_message(t('Hello world!'));
}


It’s not much but it will help us understand how to use Drush to print this statement to the terminal screen, and in doing so, how to configure the command to perform all sorts of powerful operations. We’ll be adjusting it in the course of this tutorial to demonstrate various possibilities.


The Drush command file


The first thing we need to do is add a new file to our module’s folder with the name ending in .drush.inc. Drush will scan the codebase and pick it up based on this name to load the functions we declare inside.


It is also best practice to name this file after the module you place it in. For our case, this would be demo_drush.drush.inc (my module’s name is demo_drush). And for now, just open php tags (<?php) at the top and save the file.


Command hook and callback


There are 2 main components in the Drush command architecture: the hook implementation where we define the commands and their configurations, and the callback functions that get triggered by the command. There are of course other functions that get called in the process (such as validation or pre/post callbacks), but we will not cover them in this tutorial.


First, let’s implement hook_drush_command() and define a simple command called drush-demo-command with an alias of ddc:


Continue reading %Drupal: How to Create Your Own Drush Command%




more

{ 0 comments... » Drupal: How to Create Your Own Drush Command read them below or add one }

Post a Comment

Popular Posts