You are here

Example: Hooks in Examples for Developers 8

Same name and namespace 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

hooks_example/hooks_example.module, line 14
Examples demonstrating how to implement and invoke hooks.

Functions

Classes

Namesort descending Location Description
HooksExampleTest hooks_example/tests/src/Functional/HooksExampleTest.php Test the functionality of the Hooks Example module.