After #1813762: Introduce unified interfaces, use dependency injection for interface translation and the fact that string translation itself is now a service, anyone can inject it to a class and use it directly instead of t(), thus making the class unit-testable.
The recommended/supported way to work with injected translation in Drupal 8 so that our string extractor can find them is by using a protected t()
method inside the class.
FormBase and ControllerBase already provide one.
If your class is neither a controller or form, you can use the StringTranslationTrait
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 fallback 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');
// ...
}
}
Passing strings to anything else than t() or $this->t()
eg. $this->stringTranslation->translate('Something')
won't work, it will not be possible to provide translation for that on localize.drupal.org