实现hook_filter()

老葛的Drupal培训班 Think in Drupal

现在模块的基本部分已经有了,让我们在creativejuice.module中添加我们的hook_filter()实现:
 
/**
 * Implementation of hook_filter().
 */
function creativejuice_filter($op, $delta = 0, $format = -1, $text = '') {
    switch ($op) {
        case 'list':
            return array(
                0 => t('Creative Juice filter')
            );
 
        case 'description':
            return t('Enables users to insert random sentences into their posts.');
 
        case 'settings':
            // No settings user interface for this filter.
            break;
 
        case 'no cache':
            // It's OK to cache this filter's output.
            return FALSE;
 
        case 'prepare':
            // We're a simple filter and have no preparatory needs.
            return $text;
 
        case 'process':
            return preg_replace_callback("|\[juice!\]|i",
                'creativejuice_sentence', $text);
 
        default:
            return $text;
    }
}
 
    过滤器API经过多个阶段,从收集过滤器的名字,到缓存,再到进行真实操作的处理阶段。通过检查creativejuice_filter(),让我们看一下这些阶段或者操作。下面是对这个钩子函数中参数的分解:
 
• $op:要执行的操作。在接下来的部分,我们将对它进行详细讨论。
 
• $delta: 一个实现hook_filter()的模块可以提供多个过滤器。你使用$delta来追踪当前执行的过滤器的ID。$delta是一个整数。由于creativejuice模块仅提供了一个过滤器,所以我们可以忽略它。
 
• $format:一个整数,表示正被使用的是哪一个输入格式。Drupal对这些的追踪是在filter_formats数据库表中进行的。
 
• $text:将被过滤的内容。
 
    根据$op参数的不同,可执行不同的操作。

Drupal版本: