PHP8有一个新的很酷的"enum“特性,它应该取代所有的类常量,从而使编码更容易、更安全。我提到的一个问题是,许多常见的Drupal特征(最重要的是翻译特性)都具有属性,因此不能在枚举中使用。
所以我想做的是
$this->t('summer'), // can't use OOP here :(
Season::WINTER => $this->t('winter'),
};
}
}我知道我仍然可以使用老式的程序代码。
return match ($this) {
Season::SUMMER => t('summer'), // that's what we did 20 years ago
Season::WINTER => t('winter'),
};但是有没有“更漂亮”的方法呢?我在一个D10/PHP8 8项目中,程序代码是双支持的,但是在Drupal生态系统中,具有属性的特性非常常见。特别是获取常量的可翻译标签是非常常见的用例。
使用/注射Drupal性状(特别是StringTranslationTrait)的推荐方法是什么?
发布于 2023-03-23 16:20:55
根据apaderno的注释,您可以自己实例化类,而不是使用Drupal创建TranslatableMarkup实例。
use Drupal\Core\StringTranslation\TranslatableMarkup;
enum Season: string {
case SUMMER = 'summer';
case WINTER = 'winter';
public function getLabel(): TranslatableMarkup {
return match ($this) {
Season::SUMMER => new TranslatableMarkup('summer'),
Season::WINTER => new TranslatableMarkup('winter'),
};
}
}https://drupal.stackexchange.com/questions/315174
复制相似问题