initphp/translator 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

initphp/translator

Composer 安装命令:

composer require initphp/translator

包简介

Micro multi-language (i18n) translation library for PHP with file or directory based language packs, dot-delimited nested keys, placeholder interpolation and default-language fallback.

README 文档

README

A micro multi-language (i18n) translation library for PHP. Load language packs from plain PHP files, look up keys (including dot-delimited nested keys), interpolate {name} placeholders, and fall back to a default language when a translation is missing.

Latest Stable Version Total Downloads License PHP Version Require

Features

  • Two on-disk layouts: one file per language, or one directory per language.
  • Nested keys via dot notation (admin.dashboard, errors.http.404).
  • Placeholder interpolation (Welcome {user}) from a context map.
  • Fallback chain: active language → inline fallback → default language → the key itself.
  • No runtime dependencies. Loaded languages are cached in memory.

Requirements

  • PHP 8.1 or higher

Installation

composer require initphp/translator

Quick start

require_once 'vendor/autoload.php';

use InitPHP\Translator\Translator;

$lang = new Translator();
$lang->setDir(__DIR__ . '/languages/')
    ->setDefault('en');

$lang->change('tr'); // switch the active language

echo $lang->translate('hello');

A language file simply returns an array:

<?php
// languages/en.php
return [
    'hello'   => 'Hello {user}',
    'today'   => "It's {day}",
];
echo $lang->translate('hello', null, ['user' => 'Ada']); // "Hello Ada"

File layout vs. directory layout

Choose how your language packs are stored. Pick the mode before loading a language (i.e. before setDefault() / change()); the default is file mode.

File mode — one file per language

languages/
    en.php
    tr.php
    fr.php
$lang = new Translator();
$lang->useFile() // optional; this is the default
    ->setDir(__DIR__ . '/languages/')
    ->setDefault('en');

echo $lang->translate('hello');

Directory mode — one directory per language

Each *.php file becomes a namespace keyed by its (lower-cased) file name, and keys are addressed as filename.key:

languages/
    en/
        user.php
        admin.php
    tr/
        user.php
        admin.php
$lang = new Translator();
$lang->useDirectory() // note: call before setDefault()/change()
    ->setDir(__DIR__ . '/languages/')
    ->setDefault('en');

echo $lang->translate('user.hello');   // user.php => ['hello' => '...']
echo $lang->translate('admin.dashboard');

How a key is resolved

translate() resolves a key in this order and returns the first hit:

  1. The active language (set by setDefault() or change()).
  2. The inline fallback string, if you passed one (it is interpolated too).
  3. The default language, when it differs from the active one.
  4. The key itself, returned verbatim, if nothing matched.
$lang->setDefault('en')->change('tr');

$lang->translate('errors.e404');                 // tr → (missing) → en → "Not Found"
$lang->translate('greeting', 'Hi {user}', [      // tr missing → inline fallback
    'user' => 'Ada',
]);                                              // "Hi Ada"
$lang->translate('unknown.key');                 // nowhere → "unknown.key"

Note: a key that points to a nested array (a namespace) rather than a string is treated as a miss and falls through the chain — it never throws.

Placeholders

Markers are written {name} and replaced from the context map. Scalar values and objects implementing __toString() are stringified; arrays and other objects are ignored, and unmatched markers are left untouched.

$lang->translate('errorMsg', null, ['code' => 2005]);
// "Something went wrong. Code : 2005"

Methods

Method Description
setDir(string $dir): self Sets the base directory of the language packs. Trailing slashes are trimmed. Throws if the path is not a directory.
useFile(): self Selects file mode (default). Call before loading a language.
useDirectory(): self Selects directory mode. Call before loading a language.
setDefault(string $default): self Sets and loads the default (fallback) language; becomes the active one if none is set.
change(string $current): self Switches the active language, loading it on first use.
translate(string $key, ?string $fallback = null, array $context = []): string Returns the resolved, interpolated translation.
render(string $key, ?string $fallback = null, array $context = []): void Echoes the value of translate().
_r(...) Deprecated alias of translate(), kept for backward compatibility.
_e(...) Deprecated alias of render(), kept for backward compatibility.

All configuration methods return $this, so calls can be chained.

Documentation

Full guides with examples live in docs/:

Getting help

If you have questions, bug reports, or feature requests, please open an issue in the issue tracker.

Contributing

All contributions to this project will be published under the MIT License. By submitting a pull request or filing a bug, issue, or feature request, you are agreeing to comply with this waiver of copyright interest.

Before opening a pull request, run the full local check bundle:

composer ci   # cs-check + stan + test
  • Fork it ( https://github.com/InitPHP/Translator/fork )
  • Create your feature branch (git checkout -b feat/my-feature)
  • Commit your changes (git commit -am 'Add some feature')
  • Push to the branch (git push origin feat/my-feature)
  • Create a new Pull Request

Credits

License

Copyright © 2022 InitPHP — released under the MIT License.

initphp/translator 适用场景与选型建议

initphp/translator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 122 次下载、GitHub Stars 达 3, 最近一次更新时间为 2022 年 04 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「i18n」 「translation」 「language」 「l10n」 「translator」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 initphp/translator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 initphp/translator 我们能提供哪些服务?
定制开发 / 二次开发

基于 initphp/translator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 122
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 18
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 2
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-04-24