在PHP中翻译模型异常 - Zf2 - Zend i18n - Poedit

时间:2015-11-06 15:54:09

标签: php internationalization zend-framework2 poedit zend-translate

如何在我的模块/模型中翻译自定义异常?什么是最好的方式?

1)直接进入MyModelTableGetaway.php。例如:

 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;
 }

我会告诉poedit考虑所有内部__()

2)创建一个文件夹MyModel / languages / language_than_i_want ,在这个文件夹中,我可以放置一个带有异常数组的文件.php

什么是更好更快?还有其他方法吗?

非常感谢

1 个答案:

答案 0 :(得分:1)

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: