I clearly remember the moment of excitement and joy couple of years ago when I discovered drush. Interacting with drupal from the command line? Wow! This was definitely something new to me, never seen it before in any cms.
Digging more, I discovered the wp-cli for the wordpress, but it seems that this in no way as mature as drush.
I use drush on a daily basis. For simple tasks such as clearing the caches or updating a feature to more complex stuff like in a deployment process or as an interactive php shell.
As with drupal, drush can also be extended. It is just a matter of writing the proper hook in the proper file. It is really simple and everyone can write their own drush commands.
As an example, I am going to show you how you to trigger a node save.
First, we will need a drush command file.
The drush command file must end with .drush.inc It can be placed in a number of locations. One common place is the drush folder in your home directory: ~/.drush If you put the drush command file in that directory, your commands will be available for all your projects. Another option is to create a module and add your command file to the module folder. This is more preferable if the command functionality is specific for a project.
In this file, we are going to implement the hook_drush_command() hook. This hook defines the drush command
We will replace hook with the module name and use the same name for the first part of the command file:
Hook function: mymodule_drush_command()
The hook_drush_command() hook contains a description of the drush command:
* Implements hook_drush_command().
$items['custom-save-node'] = array(
'description' => "Triggers a node-save",
'arguments' => array(
'nid' => 'The nid',
'aliases' => array('cns'),
'examples' => array(
'drush save-node 12' => 'Triggers a asve for the node with nid=12',
This is self explanatory. Now we need to write the php code to be executed when the above command is run:
Naming is important here. We always need to prefix with drush_ following by the hook name and the command name.
That’s all. Now, when we type drush custom-save-node 12, the node with nid=12 will be saved.
Now, let’s say that you want to perform another action before saving this node. You can implement the validate hook:
//check that this node is of certain type and return error if not:
drush_set_error('You can not save this node.');
There are a few hooks that are executed before and after your command, here are some:
To see all hooks, run drush custom_save_node --show-invoke
Similarly, implementing those those hooks for other commands, we can alter their functionality. For example, prevent the drush dis command from disabling the webform module:
drush_set_error('You can not uninstall webform module);
Did you like this post? Drop me a line in the comments below