sagittariusx / beluga.translation
PHP翻译/本地化库
0.1.1
2016-08-24 09:17 UTC
Requires
- php: >=7.0
- sagittariusx/beluga.dynamic-properties: ^0.1.0
This package is not auto-updated.
Last update: 2024-09-13 21:38:29 UTC
README
PHP翻译/本地化库
安装
通过以下方式安装
composer require sagittariusx/beluga.translation
或在 composer.json
内部
"require": { "sagittariusx/beluga.translation": "^0.1.1" },
使用方法
如果您想在应用程序内使用此包,请包含相应的composer autoload.php
第一步,地区设置
创建一个新的地区实例
use \Beluga\Tranlation\Locale; Locale::Create( // The fallback locale if no other was found new Locale( 'de', 'AT', 'UTF-8' ), // Check also the URL path for an locale or language part? true, // This are the names of the parameters, accepted from $_POST, $_GET and $_SESSION [ 'locale', 'language', 'lang' ] ) ->registerAsGlobalInstance();
这会通过检查以下位置来创建新的地区,以获取所需的信息
- 首先检查当前URL部分,如果其中包含有效的地区字符串,则使用它(您可以通过将第2个创建参数设置为FALSE来禁用此功能)。
- 接下来检查是否定义了请求参数(第3个参数),这些参数通过 $_POST、$_GET 或 $_SESSION 定义。
- 之后,它会检查浏览器是否发送有关首选地区/语言的某些信息。
- 最后,它会检查系统是否提供了可用的地区信息。
如果所有这些方法都失败,则返回声明的回退地区。您也可以称之为主地区。
最后但同样重要的是,创建的地区被注册为全局可用的地区实例。您可以通过以下方式从其他地方访问它
if ( Locale::HasGlobalInstance() ) { $locale = Locale::GetGlobalInstance(); } else { // Create the locale //$locale = Locale::Create( … )->registerAsGlobalInstance(); }
在您的应用程序或库内部
例如,如果您有一个需要本地化的类
use \Beluga\Translation\{Locale,Translator}; use \Beluga\Translation\Source\ArraySource; class Foo { /** * @type \Beluga\Translation\Translator */ private $trans; public function __construct( Locale $locale = null ) { $_locale = null; if ( ! \is_null( $locale ) ) { $_locale = $locale } else if ( Locale::HasGlobalInstance() ) { $_locale = Locale::GetGlobalInstance(); } if ( ! \is_null( $_locale ) ) { $source = ArraySource::LoadFromFolder( __DIR__ . '/i18n', $_locale, false ); $this->trans = new Translator( $source ) } } public function getTranslation( $mainLanguageText ) { if ( ! ( $this->trans instanceof ITranlator ) ) { return $mainLanguageText; } return $this->trans->translateByText( $mainLanguageText ); } }