For most tasks you'll find a suitable drupal class to extend from which has $this->t()
defined, but if you need to build your own class from scratch best practice would be to use the string translation trait and inject this as service if you use this class in a service context.
Here is an example How to inject translator service in custom services or controllers in Drupal 8 using the StringTranslationTrait to get t() and formatPlural() methods.
Example:
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
class MyClass {
use StringTranslationTrait;
/**
* Constructs a MyClass object.
*
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation service.
*/
public function __construct(TranslationInterface $string_translation) {
// You can skip injecting this service, the trait will fall back to \Drupal::translation()
// but it is recommended to do so, for easier testability,
$this->stringTranslation = $string_translation;
}
/**
* Does something.
*/
public function doSth() {
// ...
$string = $this->t('Something');
// ...
}
}