When your custom module or theme start to get bigger and you add a lot of hooks in your .module or .theme files it becomes unreadable and hard to maintain with thousands of code lines.
One of the solutions to this problem is to create a class for a set of hooks and a function for each hook in that class.
To explain this let's take for example the block api hooks like : hook_block_access, hook_block_alter, etc..
You can create a class called BlockHandler inside your src folder like the following:
<?php
namespace Drupal\MY_MODULE;
use Drupal\block\Entity\Block;
use Drupal\Core\Session\AccountInterface;
/**
* Class BlockHandler
*
* @package Drupal\MY_MODULE
*/
class BlockHandler {
/**
* Allow modules to alter the block plugin definitions.
*
* @param array $form
* The array of block definitions, keyed by plugin ID.
*/
public function blockAlter(array &$definitions) {
// Your custom code here.
}
/**
* Control access to a block instance.
*
* @param \Drupal\block\Entity\Block $block
* The block instance.
* @param string $operation
* The operation to be performed; for instance, 'view', 'create', 'delete', or 'update'.
* @param \Drupal\Core\Session\AccountInterface $account
* The user object to perform the access check operation on.
*/
public function blockAccess(Block $block, $operation, AccountInterface $account) {
// Your custom code here.
}
}
Add your hooks in .module file like this:
<?php
/**
* @file
* Contains MY_MODULE.module.
*/
use Drupal\MY_MODULE\BlockHandler;
/**
* Implements hook_block_access().
*/
function MY_MODULE_block_access($block, $operation, $account) {
return \Drupal::service('class_resolver')
->getInstanceFromDefinition(BlockHandler::class)
->blockAccess($block, $operation, $account);
}
/**
* Implements hook_block_alter().
*/
function MY_MODULE_block_alter(&$definitions) {
return \Drupal::service('class_resolver')
->getInstanceFromDefinition(BlockHandler::class)
->blockAlter($definitions);
}
Now your .module file is more readable and maintainable with clear code.