Documentation menu

Application services

Localisation

Taphra translates messages from YAML catalogs in app/Translations/, with ICU plural and select rules, and formats numbers for the active locale. The engine is the taphra/l10n package, Taphra\L10n; inside an app it is configured from app.yml. Its full API, for use without the framework, is in the package README.

Contents

#

Locales and catalogs

#

app.locale is the default locale (en when unset) and app.fallback_locale the locale used for keys a catalog lacks (also en when unset):

YAML
all:
  locale: en
  fallback_locale: en
  supported_locales: [en, fr]   # read by LocaleMiddleware, below

Each locale has one YAML file in app/Translations/, named after the locale (en.yml, fr.yml, fr_CA.yml). The skeleton has no such folder; create it with your first catalog. Keys can be nested; they are read as dot-notation keys (cart.items):

app/Translations/en.yml
welcome: "Welcome, {name}!"
nav:
  home: Home
cart:
  items: "{count, plural, =0{Your cart is empty} one{# item in your cart} other{# items in your cart}}"
app/Translations/fr.yml
welcome: "Bienvenue, {name} !"
cart:
  items: "{count, plural, =0{Votre panier est vide} one{# article dans votre panier} other{# articles dans votre panier}}"
"Sign out": "Se déconnecter"

A lookup for fr_CA tries fr_CA.yml, then fr.yml, then the fallback locale. The catalogs are compiled to PHP arrays in app/tmp/lang_cache/ on first use and rebuilt when a YAML file changes; php taphra optimize builds them all at deploy time.

Translating messages

#

__($key, $replace = [], $context = null) is the global shorthand for L10n::tr(). It works in controllers, views and any other code:

PHP
use Taphra\L10n;

echo __('welcome', ['name' => 'Ada']), "\n";   // Welcome, Ada!

L10n::setLocale('fr');
echo __('welcome', ['name' => 'Ada']), "\n";   // Bienvenue, Ada !
echo __('nav.home'), "\n";                      // Home: fr.yml has no nav.home, so the fallback (en) answers
echo __('Sign out'), "\n";                      // Se déconnecter
echo __('Not translated yet'), "\n";            // Not translated yet

L10n::setLocale('en');
  • {name} placeholders are filled from $replace.
  • A key no catalog has is returned as the message itself, formatted with $replace. So a message can be named by its source text (__('Sign out')), gettext style: the source language needs no catalog, and a missing translation shows the source text. Misses are written to the app log at notice level.
  • $context tells two meanings of the same source text apart: __('Order', [], 'verb') reads the _context.verb.Order entry.

In a view, echo the result through e() when the message or its values can contain user text: <?= e(__('welcome', ['name' => $user['name']])) ?>. A translation is a plain string and is not escaped by __().

Plurals and selects

#

A message with an ICU plural, select, selectordinal or number argument is formatted as ICU MessageFormat. # is the number, formatted for the locale; =0 matches an exact value:

PHP
use Taphra\L10n;

echo __('cart.items', ['count' => 0]), "\n";      // Your cart is empty
echo __('cart.items', ['count' => 1]), "\n";      // 1 item in your cart
echo __('cart.items', ['count' => 1500]), "\n";   // 1,500 items in your cart

L10n::setLocale('fr');
echo __('cart.items', ['count' => 1500]), "\n";   // 1 500 articles dans votre panier
L10n::setLocale('en');

With ext-intl loaded, PHP's MessageFormatter applies every CLDR plural rule and the locale's digits. Without it, a built-in formatter covers the common language families (one and other, French-style 0 and 1, Slavic few and many, Arabic six forms and more) with Latin digits; the package README lists them. Install ext-intl in production when you support languages outside that list.

Numbers and dates

#

L10n::number($number, $decimals) formats a number with the active locale's separators:

PHP
use Taphra\L10n;

$en = L10n::number(1234567.891, 2);   // "1,234,567.89"
L10n::setLocale('de');
$de = L10n::number(1234567.891, 2);   // "1.234.567,89"
L10n::setLocale('en');

L10n has no date formatter of its own. With ext-intl loaded, an ICU date argument in a message formats a Unix timestamp, as in "Paid on {paid, date, long}" with ['paid' => $timestamp]; pass the timestamp as an integer, since other values (a DateTime object among them) are formatted as an empty string. Without ext-intl the number is printed as it is. For more control, use PHP's IntlDateFormatter with L10n::locale().

Choosing the locale for a request

#

L10n::setLocale($locale) sets the locale for the rest of the request. It accepts BCP 47 (fr-CA) and underscore (fr_CA) forms and throws InvalidArgumentException for anything that is not a locale tag, such as ../etc or en.UTF-8, so a value from the URL cannot name another file. Check user input with L10n::isValidLocale(), and against the locales you support, before you pass it on.

Taphra\Http\LocaleMiddleware picks the locale for the routes of a route group. It takes the first of these that is a valid, supported locale:

  1. the lang query parameter (?lang=fr),
  2. the taphra_locale cookie,
  3. the Accept-Language header, best match first, trying fr for fr-CA,
  4. the current locale (app.locale).

The middleware removes every character other than letters, digits, - and _ from a candidate, then skips it unless it is a valid locale tag. app.supported_locales (or a list passed to the constructor) limits the choice further. Set it: with no list, any well-formed tag is accepted, so ?lang=xyz selects a locale that has no catalog and every message comes from the fallback locale. The locale is also available as the locale request attribute.

app/Config/routes.yml
groups:
  shop:
    prefix: /shop
    middleware: [Taphra\Http\LocaleMiddleware]
    routes:
      GET /cart: shop/cart
app/Controllers/ShopController.php
<?php
// app/Controllers/ShopController.php
namespace App\Controllers;

use Taphra\L10n;

class ShopController extends AppController
{
    public function cart(): string
    {
        return e(L10n::locale() . ': ' . __('cart.items', ['count' => 3]));
    }
}

GET /shop/cart?lang=fr answers fr: 3 articles dans votre panier; a browser that sends Accept-Language: fr-CA,fr;q=0.9 gets the French catalog too.

Two things to know in 1.0:

  • On the standard entry (app/Static/index.php creating a FrontController), route middleware runs as a gate before the action. The locale the middleware picks applies, but the taphra_locale cookie it adds to its response is not sent. To remember a visitor's choice, set the cookie yourself where they pick a language: Cookie::set(LocaleMiddleware::COOKIE_NAME, $locale, 31536000). The middleware reads it on the following requests. In a PSR-15 pipeline for every request, add new LocaleMiddleware() before ActionDispatcherMiddleware: there it runs on every route and its cookie is sent.
  • Under FrankenPHP worker mode the active locale goes back to the boot locale before each request, so a locale one request set does not carry over to the next. To force one locale for every request, call L10n::setLocale(Config::get('app.locale', 'en')) in your base controller's beforeAction().

Finding missing translations

#

php taphra lang:scan reads the PHP files and templates under app/, collects the literal keys passed to __() and L10n::tr(), and lists the ones a locale's catalog lacks:

Shell
php taphra lang:scan fr             # keys used in app/ that fr.yml (and its fallbacks) lack
php taphra lang:scan fr --orphans   # also keys in the catalog that no code uses

It exits with status 1 when keys are missing, so it can fail a CI job. Keys built at run time (__($key), __('status.' . $name)) cannot be found by reading the code and are skipped.