该软件包最新版本(0.1.0)没有提供许可信息。

PHP中简单i18n管理的库

0.1.0 2017-09-11 07:39 UTC

This package is auto-updated.

Last update: 2024-09-14 09:53:14 UTC


README

PHP中简单i18n管理的库。

安装

在您的项目 composer.json 中将 openclerk/i18n 包作为依赖项,然后运行 composer update 以将其安装到您的项目中

{
  "require": {
    "openclerk/i18n": "dev-master"
  }
}

功能

待办事项

使用

I18n::addAvailableLocale(new FrenchLocale());   // implement your own Locale here

I18n::setLocale('fr');
echo t("hello");                  // returns 'bonjour'
echo I18n::getCurrentLocale();    // returns 'fr'

您还可以监听 i18n_missing_string 事件(使用 openclerk/events),以捕获运行时缺少的区域字符串

\Openclerk\Events::on('i18n_missing_string', function($data) {
  echo $data['locale'] . ": " . $data['key'];
});

echo t("missing string");   // prints "fr: missing string"

提供i18n字符串

实现区域的一个简单方法是在JSON文件中定义它

class FrenchLocale implements \Openclerk\Locale {

  function getKey() {
    return 'fr';
  }

  function getTitle() {
    return 'French' /* i18n */;
  }

  function load() {
    $json = json_decode(__DIR__ . "/fr.json", true /* assoc */);
    return $json;
  }

}

为了速度,您也可以将其定义为PHP文件 require()

在多个组件和项目中提供i18n字符串

通过使用 component-discoverytranslation-discovery,您可以在构建时结合多个项目和Composer依赖项的翻译文件。例如

abstract class DiscoveredLocale implements \Openclerk\Locale {

  function __construct($code, $file) {
    $this->code = $code;
    $this->file = $file;
  }

  function getKey() {
    return $this->code;
  }

  function load() {
    if (!file_exists($this->file)) {
      throw new \Openclerk\LocaleException("Could not find locale file for '" . $this->file . "'");
    }
    $result = array();
    require($this->file);
    return $result;
  }

}

class FrenchLocale extends DiscoveredLocale {

  public function __construct() {
    parent::__construct('fr', __DIR__ . "/../site/generated/translations/fr.php");
  }

}

\Openclerk\I18n::addAvailableLocales(DiscoveredComponents\Locales::getAllInstances());

(待办事项:添加示例项目链接)

在会话之间持久化区域

更改用户区域时,添加一个cookie

setcookie('locale', $locale, time() + (60 * 60 * 24 * 365 * 10) /* 10 years in the future */);

然后根据需要检查此cookie

if (isset($_COOKIE["locale"]) && in_array($_COOKIE["locale"], array_keys(I18n::getAvailableLocales()))) {
  I18n::setLocale($_COOKIE["locale"]);
}

发现翻译字符串

soundasleep/translation-discovery 项目有一个 find 脚本,可用于在项目中搜索可能需要在所有组件中翻译的翻译字符串。

此脚本将找到以下翻译字符串的所有实例,并将它们输出到 template JSON文件夹

  1. t("string")
  2. ht("string")
  3. plural("string", 1)plural("string", "strings", 1)
  4. "string" /* i18n */
  5. 以及这些模式的单引号版本