本文閱讀對象為有開發能力的Drupal開發者。Drush 是 Drupal 的一個命令行外殼和腳本接口,名副其實的瑞士軍刀,旨在使那些花費自己的工作時間在命令提示符下工作的開發者的生活更輕松。
Drush是每位Drupal開發者必不可少的工具。作者也寫過其他有關Drush的文章,可以用網站右上角的搜索框搜索一下“drush”,之前的文章基本是入門、介紹性的,比如如何使用drush清除緩存,設置默認主題等等,今天我們一起來深入一下,將drush結合到自己的模塊中去,自定義你需要的操作,幾行命令就敲完,豈不是很爽?,下面我們一起來看一下如何將drush結合進模塊中去.
首先初始化一個全新模塊(亦或者在已有模塊中),假設命名模塊名字為drush demo.
接下來,在drush_demo.module中添加以下代碼:
/**
* Example function.
*/
function demo_drush_print_statement($type = NULL) {
drupal_set_message(t('Hello world!'), $type);
}
上面代碼就如同每個新編程語言一樣,Hello World,接下來,創建一個drush_demo.drush.inc文件,也是最主要的一個文件,命名規則遵循modulename.drush.inc,在文件開頭記得添加<?php.
在開始寫drush_demo.drush.inc文件之前,先補充一個hook:hook_drush_command,該hook的作用是聲明一個新的drush command,然后我們定義一個簡單的drush命令:drush-demo-command,同時給它起一個簡稱ddc,如下代碼:
/**
* Implements hook_drush_command().
*/
function drush_demo_drush_command() {
$items['drush-demo-command'] = array(
'description' => 'Demonstrate how Drush commands work.',
'aliases' => array('ddc'),
'arguments' => array(
'type' => 'The type of statement (error or success).',
),
'options' => array(
'repeat' => 'The number of statement repeats.',
),
'examples' => array(
'drush ddc error' => 'Prints the statement once with the error flag.',
'drush ddc success --repeat=10' => 'Prints the statement 10 times with the success flag.',
),
);
return $items;
}
drush_demo.drush.inc文件的第二部分是drush的回調函數,通常以drush開頭并以下劃線鏈接剩余的部分,剩余部分來自于上面hook_drush_command鉤子中的items,比如此處的drush-demo-command,結合起來,回調函數的名字是drush_drush_demo_command(),回調函數的寫法如下:
/**
* Callback for the drush-demo-command command
*/
function drush_drush_demo_command($type = FALSE) {
// Check for existence of argument
if (!$type) {
$options = array(
'success' => dt('Success'),
'error' => dt('Error'),
);
$type = drush_choice($options, dt('What kind of message you/'d like to print?'));
}
// Check for correct argument
$correct_args = array('error', 'success');
if (!in_array($type, $correct_args)) {
return drush_set_error(dt('"@type" is not a valid statement type. Please choose between "success" and "error".', array('@type' => $type)));
}
// Option
$repeat = drush_get_option('repeat', 1);
if ($repeat > 1 && is_numeric($repeat)) {
for ($i=0; $i < $repeat; $i++) {
demo_drush_print_statement($type);
}
}
else {
demo_drush_print_statement($type);
}
}
以上便是drush結合進模塊的基本命令,使用drush cc drush命令將drush的緩存清除掉,試一下你的命令吧:drush ddc!