utopia-php/locale

一个简单的地区库,用于管理应用程序的翻译

0.6.0 2021-09-19 20:15 UTC

This package is auto-updated.

Last update: 2024-09-11 08:17:05 UTC


README

Build Status Total Downloads Discord

Utopia框架的地区库是一个简单且轻量级的库,用于管理应用程序的翻译和本地化。该库旨在尽可能简单、易于学习和使用。该库由Appwrite团队维护。

虽然这个库是Utopia框架项目的一部分,但它没有依赖关系,可以与其他PHP项目或框架独立使用。

入门指南

使用composer安装

composer require utopia-php/locale

在您的应用程序中初始化

<?php

require_once __DIR__ . '/../../vendor/autoload.php';

use Utopia\Locale\Locale;

// Init translations
Locale::setLanguageFromArray('en-US', [
    'hello' => 'Hello',
    'world' => 'World',
    'likes' => 'You have {{likesAmount}} likes and {{commentsAmount}} comments.'
]); // Set English
Locale::setLanguageFromArray('he-IL', ['hello' => 'שלום',]); // Set Hebrew
Locale::setLanguageFromJSON('hi-IN', 'path/to/translations.json'); // Set Hindi

// Create locale instance
$locale = new Locale('en-US'); // en-US will be set as default language

// Get translation
echo $locale->getText('hello'); // prints "Hello"
echo $locale->getText('world'); // prints "World"

// Use placeholders
echo $locale->getText('likes', [ 'likesAmount' => 12, 'commentsAmount' => 55 ]); // prints "You have 12 likes and 55 comments."
echo $locale->getText('likes'); // prints "You have {{likesAmount}} likes and {{commentsAmount}} comments.". If you don't provide placeholder value, the string is returned unchanged.

// Get translation of different language
$locale->setDefault('he-IL');
echo $locale->getText('hello'); // prints "שלום"

翻译的预期结构

每个翻译都是一个 键值对。键是一个标识符,代表您的应用程序中的一个字符串。值是在指定地区中的翻译。

当使用 setLanguageFromArray($code, $translations)en-US 地区设置语言时,您需要指定以下格式的翻译数组

翻译数组

<?php
    $translations = [
        'app.landing.title' => 'Welcome to My App.',
        'app.landing.cta' => 'Click Here!',
    ]

当使用 setLanguageFromJSON($code, $path)en-US 地区设置语言时,您需要指定翻译JSON文件的路径,该文件应采用以下格式

JSON文件

{
 "app.landing.title": "Welcome to My App.",
 "app.landing.cta": "Click Here!"
}

系统要求

Utopia框架需要PHP 7.4或更高版本。我们建议在可能的情况下使用最新的PHP版本。

测试

要运行测试,首先您需要安装库

docker run --rm --interactive --tty \
  --volume $PWD:/app \
  composer update --ignore-platform-reqs --optimize-autoloader --no-plugins --no-scripts --prefer-dist

最后,您可以运行测试

docker run --rm -v $(pwd):$(pwd):rw -w $(pwd) php:7.4-cli-alpine sh -c "vendor/bin/phpunit tests/Locale/LocaleTest.php"

版权和许可

MIT许可(MIT) https://open-source.org.cn/licenses/mit-license.php