开发者

How should I pass the translated text to my object in my multilingual application?

Up until now, I have maintained a 'dictionary' table in my database, for example:

+-----------+---------------------------------------+-----------------------------------------------+--------+
| phrase    | en                                    | fr                                            | etc... |
+-----------+---------------------------------------+-----------------------------------------------+--------+
| generated | Generated in %1$01.2f seconds at %2$s | Créée en %1$01.2f secondes à %2$s aujourd'hui | ...    |
| submit    | Submit...                             | Envoyer...                                    | ...    |
+-----------+---------------------------------------+-----------------------------------------------+--------+

I'll then select all rows from the database for the column that matches the locale we're interested in (or read the cache from a file to speed db lookup) and dump the dictionary into an array called $lng.

Then I'll have HTML helper objects li开发者_如何学编程ke this in my view:

$html->input(array('type' => 'submit', 'value' => $lng['submit'], etc...));
...
$html->div(array('value' => sprintf($lng['generated'], $generated, date('H:i')), etc...));

The translations can appear in PDF, XLS and AJAX responses too.

The problem with my approach so far is that I now have loads of global $lng; in every class where there is a function that spits out UI code..

How do other people get the translation into the object? Is it one scenario where globals aren't actually that bad? Would it be madness to create a class with accessors when the dictionary terms are all static?

Addendum

As I have an HTML class, a PDF class, a JSON class etc, all of which have the dictionary as a dependency, is this a situation whereby I could use dependency injection in a Lng class to make it easier to test different translations?


As a quick and simple solution just make lng a function:

 $html->input(array('type' => 'submit', 'value' => lng('submit'), etc...));

Another thought: if you're using html helpers, why don't make them aware of i18n, so that you can just pass a string ID, like

 $html->input(array('type' => 'submit', 'value' => '@submit', etc...));

and in input() function replace '@xxx' with 'lng(xxx)'

Also gettext might be an option.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜