Search code examples
phpsymfonyentitytranslation

How to use the translator service inside an Entity?


Let's say I have a User Entity :

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

With this function :

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" ?

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.


Solution

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