2

这是我提出的关于创建自己的钩子的另一个问题 的后续。

在答案和评论中,提到了两个功能

module_invoke_all(...)
drupal_alter(...)

该函数module_invoke_all似乎用于为任何实现它的模块调用钩子。

该函数drupal_alter似乎为任何实现它的模块调用一个钩子,在所有钩子函数之间传递一个持久数据结构。

挖掘代码,我还发现

module_invoke(...)

这似乎让您可以调用特定模块中的特定钩子。

所以,我的问题实际上是两个问题。首先,我对上述各项的理解是否正确。其次,是否有任何其他核心 Drupal 函数可用于调用模块中实现的钩子?

我的最终目标是更好地理解 Drupal 架构的各个部分如何组合在一起形成 Drupal,即大多数人使用的应用程序。我开始尝试孤立地理解模块系统。任何对明显误解的更正表示赞赏

4

1 回答 1

4

第一个问题:是的。

第二个问题:除了使用这些函数,也可以直接调用module_implements(),手动调用。示例用例是当您想要通过引用传递参数但不想要 drupal_alter() 强制使用的 hook_something_alter() 命名方案时。

module_implements() 返回实现给定钩子的模块数组。在 Drupal 6 中,这只是一个遍历所有模块的循环,然后检查函数 $module 是否存在。'_' 。$hook 存在。

例如,在 Drupal 7 中,可以定义 hook_yourmodule_something 可以在 anothermodule.yourmodule.inc 中,然后 Drupal 将自动查找该文件并在必要时包含它。请参阅hook_hook_info。此外,还可以更改实现挂钩的模块列表,这是相当疯狂的,应该小心使用。请参阅hook_module_implements_alter

因为这些特性使得发现比在 D6 中慢很多,所以添加了一个缓存。这基本上意味着每当您在 D7 中添加挂钩实现时,您都需要清除缓存。

手动实现示例:

<?php
// Custom hooks should always be prefixed with your module name to avoid naming conflicts.
$hook_name = 'yourmodule_something';
// Get a list of all modules implementing the hook.
foreach (module_implements($hook_name) as $module) {
  // Build the actual function name.
  $function = $module . '_' . $hook_name;
  // Call the function. Anything passed in to the function can be by-reference if the
  // hook_implementation defines it so. If you don't want that, you might want to give them
  // only a copy of the data to prevent abuse.
  $function($arg1, $arg2, $arg3, $arg4);
}
?>

If you look at the code of the functions you linked in your question, you can see that they are basically just helper function for the same procedure, so this should also help to improve the general understanding of hook calling.

于 2011-02-14T21:42:05.893 回答