【为你的打印机输入wps pin】为你的 Drupal 模块创建Drush命令

时间:2019-11-12  来源:打印机  阅读:

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) {
    $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!

PS:如果你想做更多的开发可以参考drush api以及drush官网的文档,欢迎指正校对文章内容!

【为你的打印机输入wps pin】为你的 Drupal 模块创建Drush命令

http://m.bbyears.com/bangongshuma/78690.html

推荐访问:为你等待简谱 为你所向披靡 为你等待 为你的世界开路 为你的系统配置一个默认的软件仓库 为你等候简谱 为你所困简谱
相关阅读 猜你喜欢
本类排行 本类最新