phpinternationalizationzend-framework2poeditzend-translate

Translating model exceptions in php - Zf2 - Zend i18n - Poedit


How can I translate my custom exceptions, inside my module/model? what's the best way?

1) Directly into MyModelTableGetaway.php. example:

 public function getAlbum($id)
 {
     $id  = (int) $id;
     $rowset = $this->tableGateway->select(array('id' => $id));
     $row = $rowset->current();
     if (!$row) {
         throw new \Exception(__("Could not find row $id"));
     }
     return $row;
 }

And I'll tell to poedit to consider all inside __()

2) Create a folder MyModel/languages/language_than_i_want and into this folder I can put a file .php with array of exceptions

Whats is better and fast? There are any other methods?

Thanks a lot


Solution

  • I'd go with making Zend\I18n\Translator\Translator a dependency of your class and using that. You can set that in your model/service factory (or whatever way you provision that object), e.g.:

    $translator = new Translator();
    $translator->addTranslationFile('array', 'path/to/your/translation/array.php, '', 'de);
    

    And the use it in your class:

     if (!$row) {
         throw new \Exception($translator->translate("Could not find row $id"));
     }
    

    You could also override the exception template and use translator helper in it. That might not work all the time, though.

    Other than that you'd need something to feed the translator service. I'd recommend translation array, since it'd be easier to work with than gettext.

    Relevant docs or blogposts: