我如何改进国际化代码的以下组织结构?这只是一个PoC,我在Intl :: t()中使用php intl扩展进行翻译:
index.php
1 <?php
2 //FILE translate.php, your "index.php"
3 $messages = include 'messages.php';
4 require_once 'intl.php';
5 Intl::setSource($messages);
6
7 class Foo {
8 public function throwGreeting($name) {
9 throw new Exception(Intl::t('Hello %(name)s',array('name' => $name)));
10 }
11 }
12 $foo = new Foo;
13 try {
14 $foo->throwGreeting('Anonymous');
15 }
16 catch(Exception $e) {
17 echo 'The greeting is ',$e->getMessage();
18 }
intl.php
1 <?php
2 //FILE intl.php
3 class Intl {
4 private static $messages;
5
6 /**
7 * from php.net
8 */
9 public static function t($message,$args=array()) {
10 if(array_key_exists($message,self::$messages)) {
11 $message = self::$messages[$message];
12 }
13 else {
14 //automatically queue message for translation
15 }
16 $keys = array_keys($args);
17 $keysmap = array_flip($keys);
18 $values = array_values($args);
19
20 while (preg_match('/%\(([a-zA-Z0-9_ -]+)\)/', $message, $m))
21 {
22 if (!isset($keysmap[$m[1]]))
23 {
24 throw new Exception(Intl::t("Missing argument '%(arg)s'",array('arg' => $m[1])));
25
26 }
27 $message = str_replace($m[0], '%' . ($keysmap[$m[1]] + 1) . '$', $message);
28 }
29 array_unshift($values, $message);
30 return call_user_func_array('sprintf', $values);
31 }
32 public static function setSource($src) {
33 self::$messages = $src;
34 }
35 }
messages.php
1 <?php
2 //FILE messages.php
3 return array(
4 'Hello %(name)s' => 'Hallo %(name)s',
5 );
答案 0 :(得分:1)
每次使用它时,你都会针对哈希测试字符串。那不会跑得快。但是有三个文件基本上适合模块化。
最好做点什么:
/* At top of file or in eg "myintlstrings.php" */
class Intl { public static function t(&$cache,$message,$vals) {
if ($cache==null) {
// get translated version of $message into $cache
} if (DOING_DEBUG) {
// check parameters are in vals hash
} array_unshift($vals,$cache); return call_user_func_array('sprintf',$vals);
} }
/* example 1 - function context */
static $cacheForGreeting; /* use static instead of global if in function */
throw new ExceptionIntl:t($cacheForGreeting,'Hello %(name)s'),
array('name' => $name))));
/* example 2 - global context */
global $cacheForSomethingElse; /* use global instead of static if not in function */
echo(Intl::t($cacheForSomethingElse,"And today's sales figures are:"));
答案 1 :(得分:0)
我会喜欢这个
有一个名为language的文件夹。使用键值包含po文件。
我将在PHP代码中使用密钥。在那里根据语言的选择,加载po文件。看看wordpress是如何做到的。