#! code: Drupal 11: Object Oriented Hooks And Hook Service Classes

Hooks are used in Drupal to allow modules and themes to listen to or trigger different sorts of events in a Drupal system. During these events Drupal will pause and ask if any modules want to have any say in the event that is currently being triggered.

For example, hooks are commonly used when content is viewed, created, updated, or deleted. So, if we delete a page of content then a delete hook is triggered which allows modules to react to that content item being deleted. Using this, we can react to this and perform clean up operations on items of content that don't exist any more. Our custom module might want to remove items from a database table, or delete associated files since they wont be needed.

This is just one example of how hooks are used in Drupal as they are used in all manner of different situations, and not just listening for content events. Another example of a common Drupal hook is when creating a custom template. Many modules will use a hook called hook_theme() to register one or more templates with the theme system so that they can be used to theme custom content.

Hooks have been used in Drupal for a long time (probably since version 3) and have always been one of the harder things for beginners to understand. Module files full of specially named functions that seem to be magically called by Drupal is not an easy concept to get into and can take a while to get familiar with.

New in Drupal 11.1.0 is the ability to create object oriented (OOP) hooks, which is a shift away from the traditional procedural based hooks that have been a part of Drupal for so long. This OOP approach to hooks can be used right now, has a backwards compatible feature, and will eventually replace procedural hooks (where possible).

In this article we will look at how to create a OOP hook, how to transition to using OOP hooks in your Drupal modules, and how to create your own OOP hooks.

Read more

PubDate

Tags