Cms技巧
分享创造价值 合作实现共赢

Cms技巧

当前位置: 首页 > 新闻动态 > Cms技巧

为你的 Drupal 模块创建Drush命令

发布时间:2019-12-16 11:15:58作者:admin点击:

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。在文件开头记得添加
在开始写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) {

TOP

QQ客服

18910140161