开发者

Optimize Internationalization script, do i made the good choice?

I'm going ahead to develop the localization files for my project and i am not sure if i am doing the good choice.

<?php
$translation= array(
    "sentence" => array ("fr" => "phrase", "it" => "frase")
);

function _($toTranslate = '', $lang = 'en'){

    if($toTranslate != ''){

        if(!array_key_exists($toTranslate[$lang], $translation))
            return $toTranslate;

        els开发者_StackOverflow社区e 
            return ${$lang}[$toTranslate];
    }
}
?>

I clearly no idea to know if i am doing it well.


Not good enough.

  1. Improvement to your implementation.

Place each language in an single file would be better for performance and maintenance. For example, make a folder called "language", it contains "fr.inc.php", "de.inc.php" and so on. In the config file, you have a line like

$config['language'] = 'de';

You can also load the language code from GET parameter:

$config['language'] = htmlspecialchars($_GET['lang']);

Remember to have check if the language file exists or not (file_exists())

In your bootstrap code, you load the language file (check it before)

require_once LANGUANGE_DIR . '/' . $config['language'] . '.inc.php';

and when you need the language resource string, you call your "_" function, now it should look like

function _($LANG_RES_ID) {
    global $lang;
    return isset($lang[$LANG_RES_ID] ? $lang[$LANG_RES_ID] : $LANG_RES_ID;
}

2 Use gettext

see php.net: http://www.php.net/gettext

Also, many open source apps are good cases for study, phpMyAdmin, for example.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜