PHP8 has that new cool "enum" feature that should replace all class constants and would make coding easier and safer. One problem I encoutered is that many common Drupal traits (foremost the translation trait) have properties and therefore can not be used in enums.
So what I would like to do is
<?php
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
enum Season: string {
// Can't use this because that trait has a property
// and enums can only use traits without properties.
use StringTranslationTrait;
case SUMMER = 'summer';
case WINTER = 'winter';
public function getLabel(): TranslatableMarkup {
return match ($this) {
Season::SUMMER => $this->t('summer'), // can't use OOP here :(
Season::WINTER => $this->t('winter'),
};
}
}
I know that I can still use old-school procedural code
return match ($this) {
Season::SUMMER => t('summer'), // that's what we did 20 years ago
Season::WINTER => t('winter'),
};
but is there a "more beautiful" way? I'm on a D10/PHP8 project , procedural code is dicouraged, but traits with properties are very common in the Drupal ecosystem. Especially getting a translatable label of a constant is a very common use-case.
What is the recommended way of using/injecting Drupal traits (especially the StringTranslationTrait) into enums?