Backdrop's module system is based on the concept of "hooks". A hook is a PHP function. Each hook has a defined set of parameters and a specified result type. Hooks allow modules to interact with the Backdrop core.
Note: In module and developer documentation, the string "hook" is used as a placeholder for the module name in the hook definitions. For example, if the module file is called
example.module
, thenhook_comment_presave()
as implemented by that module would be defined asexample_comment_presave()
.
To extend Backdrop, a module need simply implement a hook. When Backdrop wishes to allow intervention from modules, it determines which modules implement a hook and calls that hook in all enabled modules that implement it.
A practical example
For example, in Backdrop when a user fills a comment field and clicks "Save", the comment is saved to the database by the function comment_save()
in comment.module
.
<?php
function comment_save($comment) {
...
// Lots of code to prepare the comment for saving.
...
// Tell the other modules a new comment is about to be saved.
module_invoke_all('comment_presave', $comment);
...
backdrop_write_record('comment', $comment); // Save the comment here.
...
}
?>
The important line concerning hooks is module_invoke_all('comment_presave', $comment)
. This line tells Backdrop to "fire" the "comment_presave" hook. Backdrop then searches in all modules for any function with the structure MODULE_NAME_comment_presave($comment)
and executes this function, passing the $comment
object as its parameter.
So in a module named better_comments.module
, a developer could implement the hook_comment_presave
hook like this:
<?php
/**
* Implements hook_comment_presave().
*/
function better_comments_comment_presave($comment) {
$comment->subject = "Hey I'm changing all titles!";
}
?>
When Backdrop is saving any comment, this function better_comments_comment_presave($comment)
will be executed, and will be passed the $comment
object - which is about to be saved - as a parameter. The hook implementation better_comments_comment_presave()
will therefore be able to modify the comment object before it is saved, and in this case will change the title of the comment being saved to "Hey I'm changing all titles!".
Note that ALL functions implementing this hook will fire; so it may be that other modules may also be attempting to modify comment subject using their own implementations of the hook. In that case, the final subject title will be determined by the module which is implemented last, based on its system weight. See hook_module_implements_alter(
) for more information about system weights.
More information about hooks
A list of all core hooks, and more information is avalable in the API Hook Documentation.