125

I am intermediate in PHP. To polish my skills I start learning Drupal 7. While learning Drupal architecture concepts, the terms hooks and bootstrapping puzzled me a lot. I read the "Pro Drupal development" book, and some documentation on drupal.org, but it is so advanced for me to learn how hooks work in Drupal to display the web page.

Can anyone tell me what hooks are in simple words?

0

14 Answers 14

113

The other answers are great, accurate, detailed, but I'm not sure they're the "simple words" explaining the bare bones of the concept that the asker was looking for.

I think of hooks as a point where the code pauses and shouts "Anyone else got anything to add here?". Any module can have a function that replies to this, and gets triggered with appropriate data passed to it at that point in the code.

A nice straightforward example is hook_node_delete(). Any module can use it to make things happen every time a node is deleted. The docs tell you this hook passes the module the object of that deleted node to work with, and outlines other useful information such as about the exact timing of when it's called (e.g. that it is before the node data is actually deleted from the database), and where in Drupal's code the hook is called (which can be more than one place).

You can explore what hooks exist and find out what data is passed to them by exploring things starting with "hook_" in the Drupal api.

Hooks work by a name conventions: using hook_node_delete as our example, when the node deletion process reaches the point where the hook is called, for every module with a function like this [modulename]_node_delete() where the word hook in the hook's name is replaced with the module's name (e.g. my_amazing_module_node_delete() ), those functions get called.

Why? So any module can do anything at these key points: for example you could look at the deleted node and do things if it meets a certain condition (say, email an administrator, or launch some long process).

Some hooks let you alter things that have been generated just before they're processed. For example, hook_menu_alter() passes you the current menu items that the system has generated. Any module can define a function some_modulename_menu_alter() and look at them, optionally change them (delete some, add some, sort them...), and pass the newly altered menu back in.

It's simple, really powerful and is at the heart of how Drupal works as a modular system. Implementations of hooks are at the heart of most Drupal modules.

When looking through the code of a Drupal module, you can spot which functions come from hooks (as opposed to functions that are simply called from within the module code itself), as the Drupal community enforce a convention whereby each implementation of a hook has a comment in front of it like this (note the "Implements hook_..." bit):

/**
 * Implements hook_some_hook().
 *
 * Some descriptive summary of what this does
 */
function my_amazing_module_some_hook() {

Some modules that act as APIs define their own hooks. For example, Views defines many hooks that allow you to add to, read and edit data at various points in the process of creating or displaying a view. You can find information about hooks created in custom modules from two places (assuming the module follows conventions etc):

  • The code and comments in the modulename.api.php file in the module folder
  • drupalcontrib.org - for example, here's their list of D7 modules they have info on, and here's their page of Views hooks

Bootstrapping is, as others explained, basically booting up - I won't duplicate the other good clear explanations.

0
55

Hooks are mostly implementations of the Visitor, and Observer patterns.

One of the most common hooks implementations is hook_menu(), which allows modules to register new paths within a Drupal system.

function my_module_menu() {
  return array('myawesomefrontpage' => array(
    'page callback' => 'function_that_will_render_frontpage'
  ));
}

A very frequent pattern in Drupal is having a [DATATYPE]_info hook, and a [DATATYPE]_info_alter hook. If you want to create a new field type, you will implement hook_field_info(); if you want to manipulate an existing one, you will implement hook_field_info_alter().

The observer pattern is object oriented, which Drupal 7 is still, mostly, not. There is however a wiki page, Drupal programming from an object-oriented perspective (Created by JonBob on April 4, 2005), which explains how Drupal uses object oriented code patterns despite this. It's interesting to note that it mentions observers, but not visitors.

This is still rather early, and is subject to change, but I want to add that while hooks have for quite some time been the de-facto standard in adding functionality to Drupal, the concept of plugins will become much more visible in Drupal 8, and will give us new ways of interacting with Core. See the relevant issue, and documentation.

0
34
+50

In layman's terms, hooks are sort of bridges which provide a way for modules to interact with each other, alter each other's structure and data, provide new data etc.

In most cases, the word hook_ in function names is replaced by the name of your module, and that provides a way for your module to tap into another module's operation. For example a drupal core module called "node" invokes various hooks. One of them is hook_node_update which gets invoked everytime an existing node is updated. When this hook is invoked, your module's (say we call it mymodule) implementation of hook_node_update is called, which in this case will be a function in your module's .module file called mymodule_node_update (Obviously this function can be in any file in your module's folder as long as it's included in the .module file as well). This hook will also be passed the necessary parameters (variables) which it can use, modify and/or return back to the function that invoked the hook.

When I first started learning Drupal, I was in the same boat as you are now, it's bit tricky to grasp at first, but once you get it, it's oh so simple and intuitive. Good luck.

2
  • 2
    thanx for your answer.it help me so much. can you please tell what is bootstrap concept in drupal and how hooks are treated in bootstraping in simple words as you explain previous answer..
    – GiLL
    Mar 24, 2012 at 11:50
  • @Bayasa, please enter your own thoughts here. I'm just adding my own. You can think about boostrtapping as starting up your computer. Drupal has many APIs, including database, files, and forms. These are based on a "platform". During bootstrap, Drupal defines these functions and the other settings (database connection, file folders, etc) so the rest of the system can continue from the rest.
    – AKS
    Jun 16, 2012 at 17:43
32

One of the core developers wrote up an article a while ago called "Drupal programming from an object-oriented perspective". It does a good job of explaining how hooks can be thought of as implementing many of the common design patterns. The best explanation of hooks comes from the article:

Drupal's hook system is the basis for its interface abstraction. Hooks define the operations that can be performed on or by a module. If a module implements a hook, it enters into a contract to perform a particular task or return a particular type of information when the hook is invoked. The calling code need not know anything about the module or the way the hook is implemented in order to get useful work done by invoking the hook.

0
21

The Bootstrap is the process Drupal goes through to build a page, basically running over all the core, theme and module code in order.
It's basically how Drupal boots up, and prepares to do it's job as CMS.

It's clever, in that it allows us to put hooks anywhere in our modules and themes, and the bootstrap process makes sure they get run at the right point.
For example if you use 'hook_form_alter' to add a custom check-box to a form, Drupal's bootstrap will make sure it runs that code, just before it renders your form.

One issue with the bootstrap is that the entire process takes time to run, even if you are only returning a small amount of data. When using Drupal with the services module as an API and returning many small XHTML or JSON responses, running through the entire bootstrap isn't very performant. Some clever people are looking at clever ways around this for Drupal 8.

But for rendering normal Drupal pages, the bootstrap process works great, it uses Drupals caching system to speed things up, and gives you total control over every part of your site. If you do find your site slow, you can always use something like APC or MemCached to help speed things up.

I hope my answer was accurate and explains things simply for you, I'm no expert, but I think that's how it works.

15

Bootstrap is the process during the which Drupal initializes itself; the process actually includes:

  • Setting the error and the exception handlers
  • Initializing the value of some spec-global variables contained in $_SERVER
  • Initializing some variables with init_set()
  • Finding the cached version of the page to serve
  • Initializing the database
  • Setting the handlers that load files when a class, or an interface is not found
  • Initializing the Drupal variables
  • Initializing the PHP session
  • Initializing the language variable
  • Loading the enabled modules

Except some operations that are specific for a Drupal version, most of the operations are independent from the Drupal version.

A hook is a PHP function that can be called from Drupal, or third-party modules, when necessary to do a task. Instead of having a prefixed list of functions to call, the list is build checking the enabled modules, and the functions they implement.
For example, Drupal uses hook_node_update(); when a node is being saved with node_save(), the following code is executed.

// Call the node specific callback (if any). This can be
// node_invoke($node, 'insert') or
// node_invoke($node, 'update').
node_invoke($node, $op);

What node_invoke() does is:

  • Getting the list of all the enabled modules
  • Checking if the enabled modules has a function whose name ends in "_node_update" and starts with the short name of the module
  • Calling that function, passing $node as parameter

Hooks can save their own data in a database, or alter the value returned from a function. The last case is, for example, what happens with hook_form_alter(), which alters the value of $form passed as reference to drupal_prepare_form().

Drupal hooks are generally invoked using three functions:

drupal_alter() is the function used to invoke specific hooks whose purpose is to alter the data passed them as reference, such as hook_form_alter(), hook_hook_info_alter(), and hook_tokens_alter().

There are other functions that are used to invoke hooks, such as node_invoke(), but those functions essentially use one of the functions I listed before.

11

Hooks are pointcuts and module_invoke_all() is the weaver. (The implementation isn't clear and there are other weaving functions.) As far as I am aware, Drupal is the only system to implement AOP with PHP functions.

See also How does AOP work in Drupal? where one of the answers states:

Drupal mimics AOP paradigms through hooks, which basically allow developers to weave in bits of code during the flow of execution. You can take a look at the hooks a developer can implement on the list of Drupal hooks shown in the Drupal documentation site, which just lists the hooks invoked from Drupal core and its modules.

Putting it in different words, as another answer does:

Drupal's AOP paradigm might be better visualized as event-driven, and it all happens through Drupal's concept of hooks. For example, when you do the following:

  • Write a module called mymodule
  • In mymodule.module, create a mymodule_init() function
  • Install this module in Drupal

What you are declaring is, in pseudo-code:

subscribe mymodule to "hook events" of type init

When Drupal's core then runs module_invoke_all('init'), Drupal is saying:

notify all subscribers to "hook events" of type init that this has occurred
by passing any relevant arguments to them
and letting them run the code they define in their hook_init()

So while PHP is still a procedural language—and your mymodule_init() could do all sorts of crazy, un-encapsulated things if you really wanted—Drupal is still in charge. Drupal in a sense decides whether or not to call your code in the first place.

0
6

If you want to see the hooks Drupal lets you call, go to api.drupal.org, tab over to the search box, and type 'hook_'. This will give you a big list of most of the hooks defined by Drupal. Do the same thing for '_alter' and see even more.

The Node API Hooks page offers a chronological list of all the hooks invoked during node operations. You can see the Node module and the Entity and Field systems giving each other turns at invoking hooks.

For instance, if you scroll down and look at the section for node_load(): The Node module will give you a hook_load(), and then pass control to the entity system which loads some fields. There are a whole host of field hooks not listed, and then when that's over the entity system invokes hook_entity_load(), before passing control back to Node which invokes hook_node_load().

This gives your code the chance to act on the node in question as it is loaded, piece by piece. Learning these hooks and when and why they're called is part of the adventure of Drupal coding. :-)

Other systems have hooks, too. Such as hook_init() and hook_boot(). This gets to the bootstrap part of your question. hook_boot() is invoked by Drupal before the caching system has loaded. So if your module needs to do something before Drupal has really started up, and you want your code to run regardless of caching, then you'd implement hook_boot(). Otherwise, if you only care about pages that aren't cached, you'd implement hook_init().

This gives you the option of implementing something early in the loading process, before Drupal has fully booted, while giving you some flexibility as to which point in the process you want to intercept.

If you need to make sure Drupal has booted to a certain point before you proceed, you can call drupal_bootstrap(). If you click through to that documentation you can see the bootstrap levels available, from nothing to everything.

And, finally, you can see some extensively documented code for any given subsystem at the Examples project.

0
6

Hooks are php functions, building blocks based on the naming conventions "yourmodulename_hookname", they are meant to ease developers ability to create modules.

Modules are the real deal because they enable both CORE and custom functionalities in your Drupal system. Thus, modules are made of hooks and when a module is activated in your Drupal install, its hooks functions can be called from others modules thanks to the module.inc function module_invoke_all($hook) or module_invoke.

Therefore, to properly understand what hooks are, you should really get your hands dirty and try module development. For this purpose, get started by downloading and trying some of Drupal's Examples for Developers, you should get familiar with modules creation as well.

Here are some of the useful Drupal's examples for developers mentioned above :

hook_block_view() implementation example in block_example module

/**
 * @file examples/block_example/block_example.module line 127
 *
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function block_example_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'example_configurable_text':
      // The subject is displayed at the top of the block. Note that it
      // should be passed through t() for translation. The title configured
      // for the block using Drupal UI supercedes this one.
      $block['subject'] = t('Title of first block (example_configurable_text)');

This hook give you access to Drupal's blocks creation to display custom blocks on your website. It is possible because the block.module has a _block_render_block function which enable all modules to define their hook_block view (notice the module_invoke last line):

/**
 * @file modules/block/block.module, line 838
 *
 * Render the content and subject for a set of blocks.
 *
 * @param $region_blocks
 *   An array of block objects such as returned for one region by _block_load_blocks().
 *
 * @return
 *   An array of visible blocks as expected by drupal_render().
 */
function _block_render_blocks($region_blocks) {
  ...
  foreach ($region_blocks as $key => $block) {
    ...
    $array = module_invoke($block->module, 'block_view', $block->delta);

hook_menu() implementation example in render_example module

/**
 * @file examples/render_example/render_example.module line 22
 * 
 * Implements hook_menu().
 */
function render_example_menu() {
  ...
  $items['examples/render_example/arrays'] = array(
    'title' => 'Render array examples',
    'page callback' => 'render_example_arrays',
    'access callback' => TRUE,
  );

This hook is linked to Drupal's url routing system and define url patterns with associated render callbacks used by your module. It is invoked from system.module.

About the bootstrap, basically, you just need to know it is executed on each page request. I really advise you to read this stackoverflow answer, it explains how bootstrap and hooks are related but separated.

Regarding display of the web page, Drupal's website html display is mostly achieved with render arrays and theming.

3

Anywhere a module calls module_implements() http://api.drupal.org/api/drupal/includes%21module.inc/function/module_implements/7 Drupal will fire all the correctly named functions in the right order based on their weight. These are called hook functions because in the documentation for modules that use module_implements you see things like hook_menu (for when the menu calls all functions designed to return menu items). The word "hook" just needs to be replaced with the name of the module implementing it and Drupal does the rest.

There is also a drupal_alter() function that fires all the correctly named alter functions, with the intention to let you alter things that were previously registered by another hook.

Generally alters will pass in arguments by reference so you can edit the object directly, whereas "normal" hooks usually get you to return new things.

The idea is that any module (including your own) can easily be extended by asking Drupal to call all the required hook functions and get back what they return to be processed. The module calling the hook functions doesn't need to know anything about the modules that implement the hooks, and the modules implementing the hook don't really need to know anything about the module calling the hook. The only thing both modules need to know is the structure of the data being returned or altered.

In practice hooks are most commonly usually used to:

  • respond to events, like hook_user_login is called when a user logs in
  • register something new that can be used to extend the system like hook_menu
  • theme/render html or build/validate/submit forms
1

You have a lot of answers above but i want to give an answer in much simpler way to understand the very basic concept behind hooks. Hooks are actually built in functions in drupal core to manage different things & done different jobs in core, you can synchronized your own functions with these built in functions of drupal core to add their functionality in your own functions by calling different hooks.

I hope you will get the point!

1

To me it's all about the module_implements function when it comes to hooks and core (D7). One thing that I think is crucial to understand is that by writing a hook to modify something, you by no means have the last say in what happens to the data structures you are dealing with. Your hook simply gets in the line (queue) of functions that are ALSO acting on the same data structures whether those be menus, menu_links, blocks, nodes, users or any entity or render element.

So to really see your hooks be utilized in an expected fashion you need to know or be aware of where you (your hook) stands in line. This is determined by your mondule's weight. Drupal core simply calls the properly named hooks in the ascending weight order and whatever happens to the data happens.

I've written hooks before that didn't have any effect, only to learn after hours of headbanging that my module weight was too light and sub-sequent hooks were effectively un-doing what I did or totally disregarding it all together.

A well written hook will not "man-handle" or "force" themselves to be last but will "place nice with others" by making sure they maintain the data structures as expected by the rest of the hooks down the line.

And speaking of "The Line" of hooks. Over the years I've trolled google for Drupal stuff, this image seems to be a good representation of the preprocess and process hook list of possibilties.
enter image description here

1

Hooks. Allow modules to interact with the Drupal core. Drupal's module system is based on the concept of "hooks". A hook is a PHP function that is named foo_bar(), where "foo" is the name of the module (whose filename is thus foo.module) and "bar" is the name of the hook.

0

In much simpler way, hooks help the developer to alter the existing functionality according to the requirements without making changes to the existing code. More like Abstract function in php.

Example: You have created a module for booking a bus ticket. According to your code if the ticket is once booked then pick up location is not editable which was your requirement for that project.Suppose your friend need the same module for similar requirement with exception that the user can change the pickup location. Somehow he has to use your module and you do not want him to do any code changes. So you provide a interface(hook in our case) where he could implement his changes without making changes in your module.

In drupal till drupal-7 we have hooks for modules as well as themes. To know how hook works check is drupal.org hooks to create a custom hook check this link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.