piko/i18n

一个最小化的国际化组件,可用于piko应用程序或独立使用。

v2.1 2022-11-13 21:40 UTC

This package is auto-updated.

Last update: 2024-09-14 01:54:57 UTC


README

build Coverage Status

一个最小化的国际化组件,可用于piko应用程序或独立使用。

安装

建议使用Composer安装Piko I18n。

composer require piko/i18n

用法

为了使用I18n组件,翻译必须存储在返回翻译键值对数组的PHP文件中。键是待翻译的字符串,值是相应的翻译字符串。

翻译文件示例 fr.php

return [
    'Translation test' => 'Test de traduction',
    'Hello {name}' => 'Bonjour {name}',
];

应用程序结构示例

App root
  |__messages
    |__fr.php
  |__index.php

在piko应用程序中的使用

index.php

use Piko\Application;
use function Piko\I18n\__;

require('vendor/autoload.php');

$config = [
    'basePath' => __DIR__,
    'components' => [
        'Piko\I18n' => [
            'translations' => [
                'app' => '@app/messages',
            ],
            'language' => 'fr'
        ],
    ],
];

$app = new Application($config);

$i18n = $app->getComponent('Piko\I18n');

echo $i18n->translate('app', 'Translation test') . '<br>'; // Test de traduction
echo $i18n->translate('app', 'Hello {name}', ['name' => 'John']) . '<br>' ; // Bonjour John

// Using the proxy function __() :
echo __('app', 'Translation test') . '<br>'; // Test de traduction
echo __('app', 'Hello {name}', ['name' => 'John']) . '<br>' ;  // Bonjour John

在独立脚本中的使用

use Piko\I18n;
use function Piko\I18n\__;

require('vendor/autoload.php');

$i18n = new I18n(['app' => __DIR__ . '/messages'], 'fr');

echo $i18n->translate('app', 'Translation test') . '<br>';
echo $i18n->translate('app', 'Hello {name}', ['name' => 'John']) . '<br>' ;

// Using the proxy function __() :

echo __('app', 'Translation test') . '<br>';
echo __('app', 'Hello {name}', ['name' => 'John']) . '<br>' ;