taphra / l10n
Localisation engine for PHP: dot-notation keys or source text as the key, ICU MessageFormat through intl (built-in plural subset without it), PHP-array cache.
Requires
- php: ^8.2
- symfony/yaml: ^7.0
Requires (Dev)
None
Suggests
- ext-intl: CLDR plural rules, digits and number formats (MessageFormatter, NumberFormatter); without it a built-in subset is used
Provides
None
Conflicts
None
Replaces
None
README
Documentation: https://taphra.dev/docs/packages/l10n/. This package is a read-only copy of a folder in taphra/taphra; send issues and pull requests there.
Localisation for PHP. Messages are named by dot-notation keys or by their source text (gettext style). ICU MessageFormat (plural, select, number) is formatted by PHP's intl extension when it is loaded and by a built-in subset when it is not. Translations are YAML files, cached as PHP arrays.
Requirements
- PHP 8.2+
symfony/yaml^7.0ext-intl(optional): full CLDR plural rules, digits and number formats
Installation
composer require taphra/l10n
Standalone bootstrap
When using taphra/l10n without the full Taphra framework, call L10n::configure() once before any translation calls:
use Taphra\L10n; L10n::configure([ 'locale' => 'fr', 'fallback_locale' => 'en', 'translations_path' => '/path/to/Translations', 'cache_path' => '/path/to/lang_cache', // optional; omit to disable caching ]); echo L10n::tr('auth.login'); // "Connexion" echo L10n::tr('welcome', ['name' => 'Alice']); // "Bonjour, Alice !" echo L10n::tr('messages.inbox', ['count' => 3]); // "3 messages"
with fr.yml:
welcome: "Bonjour, {name} !" auth: login: Connexion messages: inbox: "{count, plural, one{# message} other{# messages}}"
Every key in the config array is optional; only the keys present are applied. Individual setters are also available:
L10n::setTranslationsPath('/path/to/Translations'); L10n::setCachePath('/tmp/lang_cache'); L10n::setLocale('fr'); L10n::setFallbackLocale('en');
Inside the Taphra framework these paths are wired automatically from app.yml. No setup is needed beyond setting the locale in config.
Translation files
Store one file per locale in your Translations/ directory:
app/Translations/
en.yml
fr.yml
fr_CA.yml
de.yml
Files are parsed by symfony/yaml. Keys can be nested to any depth:
# Translations/en.yml welcome: "Welcome, {name}!" auth: login: Sign in errors: invalid: Invalid email or password. messages: inbox: "You have {count, plural, one{# message} other{# messages}}."
Nested keys are flattened to dot-notation on load: auth.errors.invalid, messages.inbox.
API
L10n::tr(string $key, array $replace = [], ?string $context = null): string
Translate a dot-notation key or a source text. When no catalog has it, the key itself is the message, formatted with
$replace like a translated one (placeholders, plurals).
L10n::tr('auth.login'); // "Sign in" L10n::tr('welcome', ['name' => 'Alice']); // "Welcome, Alice!" L10n::tr('messages.inbox', ['count' => 3]); // "You have 3 messages." L10n::tr('missing.key'); // "missing.key" L10n::tr('{n, plural, one {# row} other {# rows}}', ['n' => 1234]); // "1,234 rows", with no catalog L10n::tr('Done', [], 'status'); // the "_context.status.Done" entry
Source text as the key
Name a message by its text in the source language: views stay readable, the source language needs no catalog, and a message a catalog lacks falls back to the source text, formatted.
# fr.yml "Find more": "Trouver plus" "{count, plural, one {# row} other {# rows}}": "{count, plural, one {# ligne} other {# lignes}}" _context: status: "Done": "Terminé" # L10n::tr('Done', [], 'status')
L10n::setSourceLocale('en'); // English misses are the message itself: not reported to the logger L10n::setLocale('fr'); L10n::tr('Find more'); // "Trouver plus"
L10n::placeholders($message) lists a message's argument names (branches included) so a test can check that each
translation uses the same ones as its source; L10n::pluralBranches($message) and L10n::pluralCategories($locale)
check its plural branches against the language's CLDR categories.
L10n::format(string $message, array $args = [], ?string $locale = null): string
Format a message without looking it up.
L10n::has(string $key, ?string $locale = null, ?string $context = null): bool
Check whether a key exists (follows the full fallback chain).
L10n::has('auth.login'); // true L10n::has('auth.login', 'fr'); // true if fr.yml, or the fallback locale's file, has that key
L10n::catalog(?string $locale = null): array
Return the complete flat catalog for a locale (useful for debugging).
$all = L10n::catalog('en'); // ['auth.login' => 'Sign in', 'auth.errors.invalid' => '...', ...]
L10n::number(float $number, int $decimals = 0): string
Format a number with the active locale's CLDR conventions (intl's NumberFormatter when loaded, halves rounded up as
number_format() does), else its decimal and thousands separators.
L10n::setLocale('en'); L10n::number(1234567.89, 2); // "1,234,567.89" L10n::setLocale('de'); L10n::number(1234567.89, 2); // "1.234.567,89" L10n::setLocale('fr'); L10n::number(1234567.89, 2); // "1 234 567,89" (narrow no-break spaces)
L10n::setLocale(string $locale): void
L10n::locale(): string
BCP 47 dash form (fr-CA) and underscore form (fr_CA) are both accepted; the locale is stored in underscore form. A
locale set before the first lookup stays when the framework's configured locale is read (that one becomes the fallback).
Locale format and L10n::isValidLocale(string $locale): bool
A locale names files on disk (fr_CA.yml, fr_CA.php), so every method that takes one checks its shape first: a 2 or
3 letter language code, then optional subtags of up to 8 letters or digits, joined by _ or - (en, fil,
pt-BR, zh_Hant_TW, de_DE_1901, ar-u-nu-latn). setLocale(), setFallbackLocale(), setSourceLocale(), has(), catalog(),
format() and pluralCategories() throw an InvalidArgumentException for anything else (../x, en.UTF-8, e), and
the active locale stays as it was. A malformed locale in the configuration resolver is ignored.
Check user input with isValidLocale() before passing it on:
$lang = $_GET['lang'] ?? 'en'; L10n::setLocale(L10n::isValidLocale($lang) ? $lang : 'en');
Inside the framework, LocaleMiddleware picks the locale from the query string, a cookie or Accept-Language.
L10n::setSourceLocale(?string $locale): void
The language source texts are written in (also source_locale in configure() and the resolver's array).
L10n::useIntl(?bool $on): void
false forces the built-in formatter (tests, a host without intl); null, the default, uses intl when loaded.
L10n::setFallbackLocale(string $locale): void
L10n::fallbackLocale(): string
L10n::flatten(array $nested, string $prefix = ''): array
Utility to flatten a nested array to dot-notation keys. Called internally on YAML load; public for custom loaders.
Locale fallback chain
For a request locale of fr_CA:
fr_CA.yml: exact matchfr.yml: language-only parent- the fallback locale (default:
en)
Keys found in a more-specific locale take precedence over less-specific ones.
Plural rules
A message with an ICU plural, select, selectordinal or number argument is formatted as ICU MessageFormat: with
intl loaded, by its MessageFormatter (every CLDR rule, the locale's digits, so # reads "1,234" in English, "1 234"
in French and "١٬٢٣٤" in Arabic; ar_MA and ar-u-nu-latn write Latin digits); without it, by the built-in subset below
(Latin digits). Any argument name works, not only count. In such a message an int or float value of a plain {name} is
formatted as a number too (ICU's rule): pass a string to keep a year or an id as written. ICU reads an apostrophe right
before a brace as a quote: write ’ there.
# en.yml items: "You have {count, plural, one{# item} other{# items}}."
L10n::tr('items', ['count' => 1]); // "You have 1 item." L10n::tr('items', ['count' => 5]); // "You have 5 items."
Exact-value overrides:
items: "{count, plural, =0{none} one{# item} other{# items}}"
L10n::tr('items', ['count' => 0]); // "none"
Built-in subset: covered language families (used without the intl extension):
| Family | Languages | Categories |
|---|---|---|
| English-like | en, es, pt, nl, ... | one / other |
| French-like | fr, pt_BR, ... | one (0 and 1 singular) / other |
| Slavic | ru, uk, be, pl | one / few / many |
| Czech/Slovak | cs, sk | one / few / other |
| Romanian | ro | one / few / other |
| Baltic | lt, lv | one / few / other (Latvian: zero) |
| Arabic | ar | zero / one / two / few / many / other |
| Welsh | cy | zero / one / two / few / many / other |
| Irish | ga | one / two / few / many / other |
| No plural | zh, ja, ko, tr, ... | other (always) |
PHP-array cache
On first load, the YAML file is parsed and written to a PHP-array cache file ({locale}.php) in the cache path. With
OPcache enabled, later reads come from memory. A cache file older than its YAML file is rebuilt.
Inside the framework, php taphra optimize builds every translation cache at deploy time.
Missing-key logging
L10n::setLogger(function (string $message): void { error_log($message); }); // Logs: L10n: missing key "auth.missing" for locale "fr"
Package layout
packages/l10n/
composer.json
src/
L10n.php # Taphra\L10n, a single static class