Drupal 8 - Utility classes and functions


DRY (Don't repeat yourself) is a principle of software development, have you hear about that? Sometimes on Drupal while we are developing a custom module, there are some common tasks, features that we probably need to implement, instead of create our custom solutions, what if I told you that Drupal provides, let's say, a toolbox with common functions and useful classes to make our lives easier.

If there is a way that Drupal sorts some particular cases, why we just don't re-use it, it will be faster, then we are taking another advances from its framework per se. We go to try to cover must useful functions that are available to use.

  • common.inc

  • file

  • format

  • php_wrappers

  • sanitization

  • transliteration

  • validation

As you might notice there are several places where to find those classes and functions, we go to walk-throught among those places step by step, instead of create a super long article, there will be more than one to show up some details about these utility classes and functions.

Let's get start it, "php_wrappers" PHP wrapper functions, Drupal implements some custom php solutions to certain native php functions; then add improvements and secure steps, it is highly recommend to use those wrappers instead of native functions. Be aware that's possible those wrappers won't have same parameters as the original ones. The following class provide a couple of these wrappers, 

Drupal\Component\Utility\Unicode

Examples:

use Drupal\Component\Utility\Unicode;

// Converts data to UTF-8.
$utf8 = Unicode::convertToUtf8($data, $encoding);

// Counts the number of characters in a UTF-8 string.
$length = Unicode::strlen($text);

// Converts a UTF-8 string to uppercase.
$uppercase = Unicode::strtoupper($text);

// Converts a UTF-8 string to lowercase.
$lowercase = Unicode::strtolower($text);

// Capitalizes the first character of a UTF-8 string.
$ucfirst = Unicode::ucfirst($text);

// Converts the first character of a UTF-8 string to lowercase.
$lcfirst = Unicode::lcfirst($text);

// Capitalizes the first character of each word in a UTF-8 string.
$ucwords = Unicode::ucwords($text);

// Cuts off a piece of a string based on character indices and counts.
$substr = Unicode::substr($text, $start, $length);

// Truncates a UTF-8-encoded string safely to a number of characters.
$truncate = Unicode::truncate($string, $max_length, $wordsafe, $add_ellipsis, $min_wordsafe_length);

// Checks whether a string is valid UTF-8.
$valid = Unicode::validateUtf8($text);

// Finds the position of the first occurrence of a string in another string.
$strpos = Unicode::strpos($haystack, $needle, $offset);

I hope, it helps,

@see https://api.drupal.org/api/drupal/core%21core.api.php/group/utility/8.3.x

Be sure to check these notes! Since there will be living some tricks as well!