如何在实体内部使用翻译服务? [英] How to use the translator service inside an Entity?

查看:81
本文介绍了如何在实体内部使用翻译服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 User 实体:

$user = new User(007);
echo $user->getName(); // display Bond
echo $user->getGender(); // display "Male";
echo $user->getDesignation() // display "Monsieur Bond" or "Mister Bond"

使用此功能:

public function getDesignation() {
  if ($this->getGender() == 'Male') return "Monsieur ".$this->getName();
  else return "Madame ".$this->getName();
}

我如何使用该实体内部的翻译服务翻译先生并女士?

How can I use the translator service inside this Entity to translate "Monsieur" and "Madame" ?

似乎翻译器服务仅应在Controller内部使用,但在这种情况下,我认为在此Entity内部使用它是适当的。

It seems the translator service should be used only inside a Controller, but I think it's appropriate in that case to use it inside this Entity.

推荐答案

翻译器服务就像您所说的,是服务,您可以在任何类中使用服务(即,将其定义为服务)也使用依赖注入器容器)。因此,您几乎可以在任何位置使用翻译器。

The translator service is, like you say, a "service" you can use a service inside any class (i.e. defining it as a service too and using the dependency injector container). So, you can use the translator almost wherever you want.

但是像 aldo说不应该承担这种责任。在最坏的情况下,如果您真的想翻译实体内部的内容,则可以使用set方法将翻译器传递给实体,即

But the entities like aldo said shouldn't have that responsability. In the worst scenario if you really want to translate things inside the entity, you could pass the translator to the entity with a set method, i.e.

$entity->setTranslator($translator);

但是我也建议您创建一个处理实体外部问题的类,即使用树枝模板

but I recommend you too to create a class that handles the problem outside the entity, i.e. using the twig template

{{ entity.property|trans }}).

这篇关于如何在实体内部使用翻译服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆