0

I've created a few helper functions specifically for a project and I want them to be available globally.

I know I can include them via composer with the files key. I was wondering if there was a more "drupal way" sort of ...way, to include them?

2
  • Create a controller with a public funtion, you can call it anywhere with the namespace it have. Feb 16 '17 at 9:42
  • That's the way I'm currently doing it. I've created a service that has said functions. 2 of them to be exact. But it feels like a major overkill for such a simple problem. They're very simple functions which I don't feel require a service or a controller..
    – Andrew
    Feb 16 '17 at 9:44
1

The Drupal 8 way to define helper methods is to put them in a class as static methods.

Example from core:

namespace Drupal\Component\Utility;
/**
 * Provides helper methods for byte conversions.
 */
class Bytes {

  const KILOBYTE = 1024;

  /**
   * Parses a given byte size.
   *
   * @param mixed $size
   *   An integer or string size expressed as a number of bytes with optional SI
   *   or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
   *
   * @return int
   *   An integer representation of the size in bytes.
   */
  public static function toInt($size) {
    // Remove the non-unit characters from the size.
    $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
    // Remove the non-numeric characters from the size.
    $size = preg_replace('/[^0-9\.]/', '', $size);
    if ($unit) {
      // Find the position of the unit in the ordered string which is the power
      // of magnitude to multiply a kilobyte by.
      return round($size * pow(self::KILOBYTE, stripos('bkmgtpezy', $unit[0])));
    }
    else {
      return round($size);
    }
  }

}

and use it in code:

$upload_max = Bytes::toInt(ini_get('upload_max_filesize'));
0

Any functions you put in the .module file will be available globally and can be called from anywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.