在 Drupal 中,.module 文件是模块的主要部分,它包含了模块的主要 PHP 代码。虽然在 Drupal 8 及更高版本中,许多功能已经转移到其他文件和文件夹(如 src/ 文件夹和 *.yml 配置文件),但 .module 文件仍然在某些情况下是必需的。
.module 文件的主要用途有:
(1)、实现钩子(Hooks):虽然许多钩子现在可以在类中实现,但仍有一些必须在 .module 文件中实现。例如,hook_form_alter() 和 hook_theme()。
(2)、处理事件:虽然 Drupal 8 引入了 Symfony 的事件系统,但在某些情况下,使用 Drupal 的钩子系统可能更方便或更符合预期。
(3)、包含辅助函数或过程式代码:虽然 Drupal 8 鼓励面向对象编程,但在某些情况下,你可能仍然需要编写过程式代码或辅助函数。
例1:实现 hook_form_alter() 来修改一个表单
<?php
/**
* Implements hook_form_alter().
*/
function custom_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if ($form_id == 'user_register_form') {
// Modify the user registration form.
$form['account']['name']['#description'] = t('Please enter your full name.');
}
}
在这个例子中,custom_module_form_alter() 函数会检查正在被构建的表单的 ID。如果表单是用户注册表单,它会修改用户名字段的描述。
例2:实现hook_theme() 定义两个自定义的主题:test1 和 test2。每个主题都有一组预定义的变量,这些变量将在主题被渲染时传递给它。
function custom_module_theme() {
return [
'test1' => [
'variables' => ['content' => NULL,'title' => NULL,'class' => NULL,'node_url' => NULL],
],
'test2' => [
'variables' => ['content' => NULL,'title' => NULL],
],
];
}
在这个例子中,custom_module_theme() 函数定义了两个自定义的主题:test1 和 test2。每个主题都有一组预定义的变量,这些变量将在主题被渲染时传递给它。
test1主题:这个主题有四个预定义的变量:content,title,class 和 node_url。当在代码中使用这个主题时,可以传递这四个变量的值,它们将被传递给 test1 主题的模板文件(可能是 test1.html.twig)。
test2主题:这个主题有两个预定义的变量:content 和 title。当在代码中使用这个主题时,可以传递这两个变量的值,它们将被传递给 test2 主题的模板文件(可能是 test2.html.twig)。
在模板文件中,可以使用这些变量来动态地生成 HTML。例如,如果你的 test1.html.twig 文件是这样的:
<div class="{{ class }}">
<h2>{{ title }}</h2>
<a href="{{ node_url }}">Read more</a>
<div>{{ content }}</div>
</div>