Understanding Hooks in Drupal (with examples)

In this blog post, we will provide an easy-to-understand explanation of hooks in Drupal 10 along with some code examples that are compatible with PHP 8. If you're an intermediate PHP developer looking to improve your skills and start learning Drupal, this post is for you.

What are Hooks?

Hooks are a powerful feature in Drupal that allows modules to interact with the Drupal core and modify its behavior without changing the existing code. Think of hooks as points where the code pauses and asks, "Anyone else got anything to add here?". Any module can have a function that responds to this and gets triggered with the appropriate data passed to it at that point in the code.

For example, a module can use the hook_node_delete() to perform actions every time a node is deleted. Hooks work by following a naming convention: when the process reaches the point where the hook is called, every module with a function named [modulename]_node_delete() will have that function called.

Code Example: hook_node_delete()


/**
 * Implements hook_node_delete().
 */
function my_module_node_delete(\Drupal\node\NodeInterface $node): void {
  // Perform actions when a node is deleted.
  if ($node->getType() === 'article') {
    // Delete related records or perform other tasks when an article node is deleted.
  }
}

How Hooks Power Drupal's Modular System

Hooks are simple, powerful, and at the heart of how Drupal works as a modular system. Implementations of hooks are the core components of most Drupal modules. Some hooks even let you alter things that have been generated just before they're processed, giving developers the ability to easily modify the system's behavior.

Code Example: hook_form_alter()


use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(array &$form, FormStateInterface $form_state, string $form_id): void {
  if ($form_id === 'node_article_edit_form' || $form_id === 'node_article_form') {
    // Add custom validation to the article node form.
    $form['#validate'][] = 'my_module_article_form_validate';
  }
}

/**
 * Custom validation for the article node form.
 */
function my_module_article_form_validate(array &$form, FormStateInterface $form_state): void {
  // Perform custom validation on the article node form.
  if (strlen($form_state->getValue('title')[0]['value']) < 10) {
    $form_state->setErrorByName('title', t('The title must be at least 10 characters long.'));
  }
}

With these code examples, you can see how hooks are implemented in Drupal to interact with the core system and modify its behavior. As you continue to learn Drupal and explore its architecture concepts, you'll find that hooks are essential components of the Drupal ecosystem.

The Future of Drupal Hooks and Their Decreasing Importance

As Drupal continues to evolve, it is embracing a more modern approach to development, which includes a gradual shift away from hooks. This is particularly evident in the transition from Drupal 7 to Drupal 8 and 9, where the focus has been on incorporating object-oriented programming (OOP) principles, Symfony components, and the plugin system. This transition allows for better organization of code, improved reusability, and greater extensibility.

One reason for the decreasing reliance on hooks is that they can sometimes make the codebase harder to understand and maintain due to their procedural nature and global scope. The introduction of the plugin system in Drupal 8 has provided an alternative that emphasizes encapsulation and promotes the separation of concerns, making the codebase more modular and maintainable.

While hooks are still present in Drupal 9, their role is diminishing as the Drupal community increasingly adopts more modern programming practices. However, it is essential to note that hooks will not disappear entirely. They continue to play a vital role in certain areas of the Drupal ecosystem, particularly when it comes to interacting with and altering the core system. As a developer learning Drupal, it is essential to understand hooks and their place within the Drupal architecture, while also being prepared to adapt to the new paradigms that are shaping the future of Drupal development.

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!