Can you Create your Own Hook in Drupal?

拥有回忆 提交于 2019-11-29 21:02:52

Module_invoke_all() is your ticket to creating your own hooks:

see the API:

http://api.drupal.org/api/drupal/includes--module.inc/function/module_invoke_all

and then look at this great writeup:

http://web.archive.org/web/20101227170201/http://himerus.com/blog/himerus/creating-hooks-your-drupal-modules

(edit: was at http://himerus.com/blog/himerus/creating-hooks-your-drupal-modules but this is now gone)

Once you've made your hook, it can be called in another module using:

/**
 * Implementation of hook_myhookname()
 */

function THISMODULENAME_myhookname(args){
  //do stuff
}

For example, say you wanted to create hook_my_custom_goodness() for others to use. Then just place code like this in your module at the point where you want the hook to happen:

$variables['msg'] = 'foo';

// Make sure at least one module implements our hook.
if (sizeof(module_implements('my_custom_goodness')) > 0) {
  // Call modules that implement the hook, and let them change $variables.
  $variables = module_invoke_all('my_custom_goodness', $variables);
}

drupal_set_message($variables['msg']); // Will display 'bar' instead.

Now, if anybody wanted to use your hook, then they could do so in their own module like this:

/**
 * Implements hook_my_custom_goodness().
 */
function SOME_OTHER_MODULE_my_custom_goodness($variables) {
  $variables['msg'] = 'bar';
  return $variables;
}

There is a more complete explanation here:

http://tylerfrankenstein.com/code/drupal-create-custom-hook-for-other-modules

If i recall... http://api.drupal.org/api/drupal/modules--node--node.api.php/function/hook_delete/7

does ths help? been a while since I messed with Drupal.

To create/offer custom Drupal hook, you must implement in a ways such that calling the hook with module_invoke or module_invoke_all does not make any conflicts with other module hooks. The name of the hook should be unique and it should offer all/specific feature in such a general way that it doesn't require any type of adjustments with code. All the configuration must go on admin pages and should store those configurations in a separate table or any existing tables create by Drupal or modules on which your modules depends. The hook should be easy to implment by other modules and it should not be much complex to implement. When you create custom hooks, your module(s) act(s) as API provider.

For Drupal 6 & 7, drupal_alter() is probably the best option.

As stated in the module_invoke_all() documentation,

All arguments are passed by value. Use drupal_alter() if you need to pass arguments by reference.

In Drupal 8, use ModuleHandler::alter.

Passes alterable variables to specific hook_TYPE_alter() implementations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!