i18n
Overview:
i18n provides internationalization with locale management, translation loading, and parameter substitution. Uses dot-notation keys and Text::render() for template variables.
Key behavior:
- Translations are nested arrays loaded from JSON or PHP files, or directly via arrays.
- Dot-notation keys resolve to nested values:
user.profile.title. - Parameter substitution uses
{{ key }}syntax viaText::render(). - Falls back to a configurable fallback locale when a key is missing from the current locale.
- Returns the raw key string when no translation is found in any locale.
Public API:
i18n::locale($locale = null)— get or set the current locale.i18n::fallback($fallback = null)— get or set the fallback locale.i18n::t($key, $params = [])— translate a key with optional parameter substitution.i18n::load($locale, $filepath)— load translations from a JSON or PHP file.i18n::loadArray($locale, $data)— load translations from an array.i18n::has($key, $locale = null)— check if a translation key exists.i18n::all($locale = null)— get all translations for a locale.i18n::flush()— clear all loaded translations.
Example:
// Load translations
i18n::load('en', 'lang/en.json');
i18n::load('es', 'lang/es.json');
// Or load from arrays
i18n::loadArray('en', [
'user' => [
'welcome' => 'Welcome, {{ name }}!',
'logout' => 'Sign out',
],
]);
// Set locale
i18n::locale('en');
// Translate
echo i18n::t('user.welcome', ['name' => 'Alice']);
// "Welcome, Alice!"
// Fallback
i18n::locale('fr');
i18n::fallback('en');
echo i18n::t('user.welcome', ['name' => 'Bob']);
// "Welcome, Bob!" (falls back to English)
Translation file format (JSON):
{
"user": {
"welcome": "Welcome, {{ name }}!",
"logout": "Sign out"
},
"errors": {
"not_found": "Page not found"
}
}