How to use the translator service inside an Entity?

前端 未结 4 949
渐次进展
渐次进展 2021-01-12 22:07

Let\'s say I have a User Entity :

$user = new User(007);
echo $user->getName(); // display Bond
echo $user->getGender(); // display \"Male         


        
4条回答
  •  广开言路
    2021-01-12 22:27

    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.

    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 }}).
    

提交回复
热议问题