Skip to main content
4 of 8
added 138 characters in body
leymannx
  • 18.8k
  • 6
  • 72
  • 126

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_system/src/Utils/MyHelperFunctions.php

namespace Drupal\my_system\Utils;

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

  /**
   * Get current multi-site directory name.
   *
   * @return string
   *   The basename of the matching multi-site directory.
   */
  public static 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_system\Utils\MyHelperFunctions;

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

  // Add multi-site 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.

web/modules/custom/my_system/my_system.services.yml

services:
  my_system.helper_functions:
    class: Drupal\my_system\Utils\HelperFunctions

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

\Drupal::service('my_system.helper_functions')->getMultisiteAlias();

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

leymannx
  • 18.8k
  • 6
  • 72
  • 126