本文閱讀對(duì)象為有開(kāi)發(fā)能力的Drupal開(kāi)發(fā)者。Drush 是 Drupal 的一個(gè)命令行外殼和腳本接口,名副其實(shí)的瑞士軍刀,旨在使那些花費(fèi)自己的工作時(shí)間在命令提示符下工作的開(kāi)發(fā)者的生活更輕松。
Drush是每位Drupal開(kāi)發(fā)者必不可少的工具。作者也寫(xiě)過(guò)其他有關(guān)Drush的文章,可以用網(wǎng)站右上角的搜索框搜索一下“drush”,之前的文章基本是入門(mén)、介紹性的,比如如何使用drush清除緩存,設(shè)置默認(rèn)主題等等,今天我們一起來(lái)深入一下,將drush結(jié)合到自己的模塊中去,自定義你需要的操作,幾行命令就敲完,豈不是很爽?,下面我們一起來(lái)看一下如何將drush結(jié)合進(jìn)模塊中去.
首先初始化一個(gè)全新模塊(亦或者在已有模塊中),假設(shè)命名模塊名字為drush demo.
接下來(lái),在drush_demo.module中添加以下代碼:
/**
* Example function.
*/
function demo_drush_print_statement($type = NULL) {
drupal_set_message(t('Hello world!'), $type);
}
上面代碼就如同每個(gè)新編程語(yǔ)言一樣,Hello World,接下來(lái),創(chuàng)建一個(gè)drush_demo.drush.inc文件,也是最主要的一個(gè)文件,命名規(guī)則遵循modulename.drush.inc,在文件開(kāi)頭記得添加<?php.
在開(kāi)始寫(xiě)drush_demo.drush.inc文件之前,先補(bǔ)充一個(gè)hook:hook_drush_command,該hook的作用是聲明一個(gè)新的drush command,然后我們定義一個(gè)簡(jiǎn)單的drush命令:drush-demo-command,同時(shí)給它起一個(gè)簡(jiǎn)稱(chēng)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的回調(diào)函數(shù),通常以drush開(kāi)頭并以下劃線鏈接剩余的部分,剩余部分來(lái)自于上面hook_drush_command鉤子中的items,比如此處的drush-demo-command,結(jié)合起來(lái),回調(diào)函數(shù)的名字是drush_drush_demo_command(),回調(diào)函數(shù)的寫(xiě)法如下:
/**
* 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結(jié)合進(jìn)模塊的基本命令,使用drush cc drush命令將drush的緩存清除掉,試一下你的命令吧:drush ddc!