rubyrainbows / i18n
PHP 的 i18n 库
此软件包的官方仓库似乎已不存在,因此该软件包已被冻结。
1.1.1
2015-10-30 09:06 UTC
Requires
- rubyrainbows/io: 1.0.*
- symfony/yaml: 2.5.2
Requires (Dev)
- mockery/mockery: 0.9.1
- phpunit/phpunit: 4.0.20
This package is not auto-updated.
Last update: 2024-01-20 12:00:51 UTC
README
PHP I18n
PHP I18n 是一个简单的库,用于在代码外部存储本地化字符串。
安装
将以下 require 添加到您的 composer.json 文件中。
{ "require": { "rubyrainbows/i18n": "1.1.*" } }
设置
语言文件夹
为了使用 i18n,您需要一个语言文件夹。按照惯例,此文件夹为 config/locales
,但您可以选择任何您想要的。在此文件夹中,每个支持的语言都需要自己的文件夹(config/locales/en
、config/locales/de
、...)。
在 PHP 中使用
您很可能在自己的实现中会使用 I18n 类,因此您只需在您的代码中创建一个包装类即可。要创建此类,您只需提供之前决定的语言文件夹路径即可。
<?php use RubyRainbows\I18n\Lang; $lang = new Lang( dirname(__FILE__) . '/config/locales' );
示例用法
注意: 目前仅支持 yaml 文件。
对于此示例,语言文件夹位于 config/locales。
创建一个文件 config/locales/en/example.yml
foo: bar nested: foo: bar var: foo :var plural: one: A :color apple other: :count :color apples
以及一个方言文件 config/locales/en_US/example.yml
foo: murica
注意: 请注意 yml 文件名,因为它将是您键的第一个部分(example.yml => example)。
现在我们可以加载翻译类并获取我们的翻译字符串。
<?php use RubyRainbows\I18n\Lang; $lang = new Lang( dirname(__FILE__) . 'config/locales' ); /** * normal translated string * * @param string $locale * @param string $key */ $lang->get( 'en', 'example.foo' ); // returns 'bar' /** * nested translated strings * * @param string $locale * @param string $key */ $lang->get( 'en', 'example.nested.foo' ); // returns 'bar' /** * Variable translated string * * @param string $locale * @param string $key */ $lang->get( 'en', 'example.var', ['var' => 'bar']); // returns 'foo bar' /** * Plural translated strings * * @param string $locale * @param string $key * @param int $count */ $lang->get( 'en', 'example.plural', ['color' => 'red'], 1); // returns 'A red apple' $lang->get( 'en', 'example.plural', ['color' => 'red'], 2); // returns '2 red apples' /** * Dialect translated strings */ $lang->get( 'en_US', 'example.foo' ); // returns 'murica' $lang->get( 'en_US', 'example.nested.foo' ); // returns 'bar' as it falls back to en