Example: Hooks

Same name in other branches
  1. 3.x modules/hooks_example/hooks_example.module \hooks_example

Demonstrates implementing, defining, and invoking hooks.

Knowing how to implement, define, and invoke hooks is a critical concept for any Drupal developer.

Hooks are specially named functions called at key points in order to allow other code to alter, extend, and enhance the behavior of Drupal core, or another module. Without requiring changes to the original code.

Every hook has three parts; a name, an implementation, and a definition.

Hooks are implemented by following the function naming convention and reviewing the documentation associated with a hook to discover parameters and their expected values. Learn how to implement hooks by reviewing hooks_example_help(), hooks_example_node_view(), and hooks_example_form_alter() below.

Because the list of hook implementations is cached you'll need to clear the cache when first adding a new hook implementation.

Hooks are defined by creating a new, unique, hook name, providing documentation for the hook in an {MODULE_NAME}.api.php file, and using either \Drupal\Core\Extension\ModuleHandlerInterface::invokeAll(), \Drupal\Core\Extension\ModuleHandlerInterface::invoke(), or \Drupal\Core\Extension\ModuleHandlerInterface::alter() via the 'module_handler' service to call implementations of a hook in all enabled modules. Learn how to define, and invoke a new hook by reviewing hooks_example_node_view().

Learn how to document a hook by reviewing hooks_example.api.php.

Understanding hooks

In order to see this example module in action you should create one or more nodes on your site. Then visit those nodes and look for the view counter added by this module. In addition, look for the special message displayed at the top of a node the first time you view it.

See also

Hooks

\Drupal\Core\Extension\ModuleHandlerInterface

Parent topics

File

modules/hooks_example/hooks_example.module, line 14

Functions

Title Sort descending File name Summary
hooks_example_form_alter modules/hooks_example/hooks_example.module Implements hook_form_alter().
hooks_example_help modules/hooks_example/hooks_example.module Implements hook_help().
hooks_example_hooks_example_count_incremented modules/hooks_example/hooks_example.module Implements hook_hooks_example_count_incremented().
hooks_example_node_view modules/hooks_example/hooks_example.module Implements hook_ENTITY_TYPE_view().
hook_hooks_example_count_incremented modules/hooks_example/hooks_example.api.php Respond to node view count being incremented.

Classes

Title Sort descending File name Summary
HooksExampleTest modules/hooks_example/tests/src/Functional/HooksExampleTest.php Test the functionality of the Hooks Example module.