How to use helper/private methods with a .module file? Let's say I use a hook with a lot of code inside. To improve readability and reusability I'd like to use helper/private methods. However, a Drupal .module file is not a class.

The idea is to split big methods from this file into more readable and reusable smaller methods.

What is the correct way to call helper/private methods from a Drupal .module file?
I always follow Symfony standards when it comes to helper functions. I normally have one module for developer-central stuff where I add a class under src/Utils for that and then call it everywhere I need it. Also in *.module or *.theme files.

web/modules/custom/my_module/src/Utils/MyHelperFunctions.php

namespace Drupal\my_module\Utils;

/**
 * Class MyHelperFunctions.
 */
class MyHelperFunctions {

  /**
   * Get current multisite directory name.
   *
   * @return string
   *   The basename of the matching multisite directory.
   */
  public function getMultisiteAlias() {

    $site_path = \Drupal::service('site.path');
    $site      = explode('/', $site_path);

    return $site[1];
  }

}


web/modules/themes/custom/my_theme/my_theme.theme

use Drupal\my_module\Utils\MyHelperFunctions;

/**
 * Implements template_preprocess_html().
 */
function my_theme_preprocess_html(&amp;$variables) {

  // Add multisite body class.
  $site = MyHelperFunctions::getMultisiteAlias();

  $variables['attributes']['class'][] = 'site-' . $site;
}




@NoSssweat suggested that the more Drupalitically correct way to do this would be to create a service to let that method be called by other modules via dependency injection as well.

web/modules/custom/my_module/my_module.services.yml

services:
  my_module.helper_functions:
    class: Drupal\my_module\Utils\MyHelperFunctions


And then you wouldn't need to use the namespace anymore, but just can call the service wherever you want:

\Drupal::service('my_module.helper_functions')-&gt;getMultisiteAlias();




Read more: When should I create a service or a utility function?