Internationalization & Localization

One of the best ways for an application to reach a larger audience is to caterto multiple languages. This can often prove to be a daunting task, but theinternationalization and localization features in CakePHP make it much easier.

First, it’s important to understand some terminology. _Internationalization_refers to the ability of an application to be localized. The term _localization_refers to the adaptation of an application to meet specific language (orculture) requirements (i.e. a “locale”). Internationalization and localizationare often abbreviated as i18n and l10n respectively; 18 and 10 are the numberof characters between the first and last character.

Setting Up Translations

There are only a few steps to go from a single-language application to amulti-lingual application, the first of which is to make use of the__() function in your code. Below is an example of some code for asingle-language application:

  1. <h2>Popular Articles</h2>

To internationalize your code, all you need to do is to wrap strings in__() like so:

  1. <h2><?= __('Popular Articles') ?></h2>

Doing nothing else, these two code examples are functionally identical - theywill both send the same content to the browser. The __() functionwill translate the passed string if a translation is available, or return itunmodified.

Language Files

Translations can be made available by using language files stored in theapplication. The default format for CakePHP translation files is theGettext format. Files need to beplaced under src/Locale/ and within this directory, there should be asubfolder for each language the application needs to support:

  1. /src
  2. /Locale
  3. /en_US
  4. default.po
  5. /en_GB
  6. default.po
  7. validation.po
  8. /es
  9. default.po

The default domain is ‘default’, therefore the locale folder should at leastcontain the default.po file as shown above. A domain refers to any arbitrarygrouping of translation messages. When no group is used, then the default groupis selected.

The core strings messages extracted from the CakePHP library can be storedseparately in a file named cake.po in src/Locale/.The CakePHP localized library housestranslations for the client-facing translated strings in the core (the cakedomain). To use these files, link or copy them into their expected location:src/Locale/<locale>/cake.po. If your locale is incomplete or incorrect,please submit a PR in this repository to fix it.

Plugins can also contain translation files, the convention is to use theunder_scored version of the plugin name as the domain for the translationmessages:

  1. MyPlugin
  2. /src
  3. /Locale
  4. /fr
  5. my_plugin.po
  6. /de
  7. my_plugin.po

Translation folders can be the two or three letter ISO code of the language orthe full locale name such as fr_FR, es_AR, da_DK which containsboth the language and the country where it is spoken.

An example translation file could look like this:

  1. msgid "My name is {0}"
  2. msgstr "Je m'appelle {0}"
  3.  
  4. msgid "I'm {0,number} years old"
  5. msgstr "J'ai {0,number} ans"

Extract Pot Files with I18n Shell

To create the pot files from __() and other internationalized types ofmessages that can be found in the application code, you can use the i18n shell.Please read the following chapter tolearn more.

Setting the Default Locale

The default locale can be set in your config/app.php file by settingApp.defaultLocale:

  1. 'App' => [
  2. ...
  3. 'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
  4. ...
  5. ]

This will control several aspects of the application, including the defaulttranslations language, the date format, number format and currency whenever anyof those is displayed using the localization libraries that CakePHP provides.

Changing the Locale at Runtime

To change the language for translated strings you can call this method:

  1. use Cake\I18n\I18n;
  2.  
  3. // Prior to 3.5 use I18n::locale()
  4. I18n::setLocale('de_DE');

This will also change how numbers and dates are formatted when using one of thelocalization tools.

Using Translation Functions

CakePHP provides several functions that will help you internationalize yourapplication. The most frequently used one is __(). This functionis used to retrieve a single translation message or return the same string if notranslation was found:

  1. echo __('Popular Articles');

If you need to group your messages, for example, translations inside a plugin,you can use the __d() function to fetch messages from anotherdomain:

  1. echo __d('my_plugin', 'Trending right now');

Note

If you want to translate your plugins and they’re namespaced, you must nameyour domain string Namespace/PluginName. But the related language filewill become plugins/Namespace/PluginName/src/Locale/plugin_name.poinside your plugin folder.

Sometimes translations strings can be ambiguous for people translating them.This can happen if two strings are identical but refer to different things. Forexample, ‘letter’ has multiple meanings in English. To solve that problem, youcan use the __x() function:

  1. echo __x('written communication', 'He read the first letter');
  2.  
  3. echo __x('alphabet learning', 'He read the first letter');

The first argument is the context of the message and the second is the messageto be translated.

  1. msgctxt "written communication"
  2. msgid "He read the first letter"
  3. msgstr "Er las den ersten Brief"

Using Variables in Translation Messages

Translation functions allow you to interpolate variables into the messages usingspecial markers defined in the message itself or in the translated string:

  1. echo __("Hello, my name is {0}, I'm {1} years old", ['Sara', 12]);

Markers are numeric, and correspond to the keys in the passed array. You canalso pass variables as independent arguments to the function:

  1. echo __("Small step for {0}, Big leap for {1}", 'Man', 'Humanity');

All translation functions support placeholder replacements:

  1. __d('validation', 'The field {0} cannot be left empty', 'Name');
  2.  
  3. __x('alphabet', 'He read the letter {0}', 'Z');

The ' (single quote) character acts as an escape code in translationmessages. Any variables between single quotes will not be replaced and istreated as literal text. For example:

  1. __("This variable '{0}' be replaced.", 'will not');

By using two adjacent quotes your variables will be replaced properly:

  1. __("This variable ''{0}'' be replaced.", 'will');

These functions take advantage of theICU MessageFormatterso you can translate messages and localize dates, numbers and currency at thesame time:

  1. echo __(
  2. 'Hi {0}, your balance on the {1,date} is {2,number,currency}',
  3. ['Charles', new FrozenTime('2014-01-13 11:12:00'), 1354.37]
  4. );
  5.  
  6. // Returns
  7. Hi Charles, your balance on the Jan 13, 2014, 11:12 AM is $ 1,354.37

Numbers in placeholders can be formatted as well with fine grain control of theoutput:

  1. echo __(
  2. 'You have traveled {0,number} kilometers in {1,number,integer} weeks',
  3. [5423.344, 5.1]
  4. );
  5.  
  6. // Returns
  7. You have traveled 5,423.34 kilometers in 5 weeks
  8.  
  9. echo __('There are {0,number,#,###} people on earth', 6.1 * pow(10, 8));
  10.  
  11. // Returns
  12. There are 6,100,000,000 people on earth

This is the list of formatter specifiers you can put after the word number:

  • integer: Removes the decimal part
  • currency: Puts the locale currency symbol and rounds decimals
  • percent: Formats the number as a percentage
    Dates can also be formatted by using the word date after the placeholdernumber. A list of extra options follows:

  • short

  • medium
  • long
  • full
    The word time after the placeholder number is also accepted and itunderstands the same options as date.

Note

Named placeholders are supported in PHP 5.5+ and are formatted as{name}. When using named placeholders pass the variables in an arrayusing key/value pairs, for example ['name' => 'Sara', 'age' => 12].

It is recommended to use PHP 5.5 or higher when making use ofinternationalization features in CakePHP. The php5-intl extension mustbe installed and the ICU version should be above 48.x.y (to check the ICUversion Intl::getIcuVersion()).

Plurals

One crucial part of internationalizing your application is getting your messagespluralized correctly depending on the language they are shown. CakePHP providesa couple ways to correctly select plurals in your messages.

Using ICU Plural Selection

The first one is taking advantage of the ICU message format that comes bydefault in the translation functions. In the translations file you could havethe following strings

  1. msgid "{0,plural,=0{No records found} =1{Found 1 record} other{Found # records}}"
  2. msgstr "{0,plural,=0{Ningún resultado} =1{1 resultado} other{# resultados}}"
  3.  
  4. msgid "{placeholder,plural,=0{No records found} =1{Found 1 record} other{Found {1} records}}"
  5. msgstr "{placeholder,plural,=0{Ningún resultado} =1{1 resultado} other{{1} resultados}}"

And in the application use the following code to output either of thetranslations for such string:

  1. __('{0,plural,=0{No records found }=1{Found 1 record} other{Found # records}}', [0]);
  2.  
  3. // Returns "Ningún resultado" as the argument {0} is 0
  4.  
  5. __('{0,plural,=0{No records found} =1{Found 1 record} other{Found # records}}', [1]);
  6.  
  7. // Returns "1 resultado" because the argument {0} is 1
  8.  
  9. __('{placeholder,plural,=0{No records found} =1{Found 1 record} other{Found {1} records}}', [0, 'many', 'placeholder' => 2])
  10.  
  11. // Returns "many resultados" because the argument {placeholder} is 2 and
  12. // argument {1} is 'many'

A closer look to the format we just used will make it evident how messages arebuilt:

  1. { [count placeholder],plural, case1{message} case2{message} case3{...} ... }

The [count placeholder] can be the array key number of any of the variablesyou pass to the translation function. It will be used for selecting the correctplural form.

Note that to reference [count placeholder] within {message} you have touse #.

You can of course use simpler message ids if you don’t want to type the fullplural selection sequence in your code

  1. msgid "search.results"
  2. msgstr "{0,plural,=0{Ningún resultado} =1{1 resultado} other{{1} resultados}}"

Then use the new string in your code:

  1. __('search.results', [2, 2]);
  2.  
  3. // Returns: "2 resultados"

The latter version has the downside that there is a need to have a translationmessages file even for the default language, but has the advantage that it makesthe code more readable and leaves the complicated plural selection strings inthe translation files.

Sometimes using direct number matching in plurals is impractical. For example,languages like Arabic require a different plural when you referto few things and other plural form for many things. In those cases you canuse the ICU matching aliases. Instead of writing:

  1. =0{No results} =1{...} other{...}

You can do:

  1. zero{No Results} one{One result} few{...} many{...} other{...}

Make sure you read theLanguage Plural Rules Guideto get a complete overview of the aliases you can use for each language.

Using Gettext Plural Selection

The second plural selection format accepted is using the built-in capabilitiesof Gettext. In this case, plurals will be stored in the .pofile by creating a separate message translation line per plural form:

  1. # One message identifier for singular
  2. msgid "One file removed"
  3. # Another one for plural
  4. msgid_plural "{0} files removed"
  5. # Translation in singular
  6. msgstr[0] "Un fichero eliminado"
  7. # Translation in plural
  8. msgstr[1] "{0} ficheros eliminados"

When using this other format, you are required to use another translationfunction:

  1. // Returns: "10 ficheros eliminados"
  2. $count = 10;
  3. __n('One file removed', '{0} files removed', $count, $count);
  4.  
  5. // It is also possible to use it inside a domain
  6. __dn('my_plugin', 'One file removed', '{0} files removed', $count, $count);

The number inside msgstr[] is the number assigned by Gettext for the pluralform of the language. Some languages have more than two plural forms, forexample Croatian:

  1. msgid "One file removed"
  2. msgid_plural "{0} files removed"
  3. msgstr[0] "{0} datoteka je uklonjena"
  4. msgstr[1] "{0} datoteke su uklonjene"
  5. msgstr[2] "{0} datoteka je uklonjeno"

Please visit the Launchpad languages pagefor a detailed explanation of the plural form numbers for each language.

Creating Your Own Translators

If you need to diverge from CakePHP conventions regarding where and howtranslation messages are stored, you can create your own translation messageloader. The easiest way to create your own translator is by defining a loaderfor a single domain and locale:

  1. use Aura\Intl\Package;
  2.  
  3. I18n::setTranslator('animals', function () {
  4. $package = new Package(
  5. 'default', // The formatting strategy (ICU)
  6. 'default' // The fallback domain
  7. );
  8. $package->setMessages([
  9. 'Dog' => 'Chien',
  10. 'Cat' => 'Chat',
  11. 'Bird' => 'Oiseau'
  12. ...
  13. ]);
  14.  
  15. return $package;
  16. }, 'fr_FR');

The above code can be added to your config/bootstrap.php so thattranslations can be found before any translation function is used. The absoluteminimum that is required for creating a translator is that the loader functionshould return a Aura\Intl\Package object. Once the code is in place you canuse the translation functions as usual:

  1. // Prior to 3.5 use I18n::locale()
  2. I18n::setLocale('fr_FR');
  3. __d('animals', 'Dog'); // Returns "Chien"

As you see, Package objects take translation messages as an array. You canpass the setMessages() method however you like: with inline code, includinganother file, calling another function, etc. CakePHP provides a few loaderfunctions you can reuse if you just need to change where messages are loaded.For example, you can still use .po files, but loaded from another location:

  1. use Cake\I18n\MessagesFileLoader as Loader;
  2.  
  3. // Load messages from src/Locale/folder/sub_folder/filename.po
  4. // Prior to 3.5 use translator()
  5. I18n::setTranslator(
  6. 'animals',
  7. new Loader('filename', 'folder/sub_folder', 'po'),
  8. 'fr_FR'
  9. );

Creating Message Parsers

It is possible to continue using the same conventions CakePHP uses, but usea message parser other than PoFileParser. For example, if you wanted to loadtranslation messages using YAML, you will first need to created the parserclass:

  1. namespace App\I18n\Parser;
  2.  
  3. class YamlFileParser
  4. {
  5.  
  6. public function parse($file)
  7. {
  8. return yaml_parse_file($file);
  9. }
  10. }

The file should be created in the src/I18n/Parser directory of yourapplication. Next, create the translations file undersrc/Locale/fr_FR/animals.yaml

  1. Dog: Chien
  2. Cat: Chat
  3. Bird: Oiseau

And finally, configure the translation loader for the domain and locale:

  1. use Cake\I18n\MessagesFileLoader as Loader;
  2.  
  3. // Prior to 3.5 use translator()
  4. I18n::setTranslator(
  5. 'animals',
  6. new Loader('animals', 'fr_FR', 'yaml'),
  7. 'fr_FR'
  8. );

Creating Generic Translators

Configuring translators by calling I18n::setTranslator() for each domain andlocale you need to support can be tedious, specially if you need to support morethan a few different locales. To avoid this problem, CakePHP lets you definegeneric translator loaders for each domain.

Imagine that you wanted to load all translations for the default domain and forany language from an external service:

  1. use Aura\Intl\Package;
  2.  
  3. I18n::config('default', function ($domain, $locale) {
  4. $locale = Locale::parseLocale($locale);
  5. $language = $locale['language'];
  6. $messages = file_get_contents("http://example.com/translations/$lang.json");
  7.  
  8. return new Package(
  9. 'default', // Formatter
  10. null, // Fallback (none for default domain)
  11. json_decode($messages, true)
  12. )
  13. });

The above example calls an example external service to load a JSON file with thetranslations and then just build a Package object for any locale that isrequested in the application.

If you’d like to change how packages are loaded for all packages, that don’thave specific loaders set you can replace the fallback package loader by usingthe _fallback package:

  1. I18n::config('_fallback', function ($domain, $locale) {
  2. // Custom code that yields a package here.
  3. });

New in version 3.4.0: Replacing the _fallback loader was added in 3.4.0

Plurals and Context in Custom Translators

The arrays used for setMessages() can be crafted to instruct the translatorto store messages under different domains or to trigger Gettext-style pluralselection. The following is an example of storing translations for the same keyin different contexts:

  1. [
  2. 'He reads the letter {0}' => [
  3. 'alphabet' => 'Él lee la letra {0}',
  4. 'written communication' => 'Él lee la carta {0}'
  5. ]
  6. ]

Similarly, you can express Gettext-style plurals using the messages array byhaving a nested array key per plural form:

  1. [
  2. 'I have read one book' => 'He leído un libro',
  3. 'I have read {0} books' => [
  4. 'He leído un libro',
  5. 'He leído {0} libros'
  6. ]
  7. ]

Using Different Formatters

In previous examples we have seen that Packages are built using default asfirst argument, and it was indicated with a comment that it corresponded to theformatter to be used. Formatters are classes responsible for interpolatingvariables in translation messages and selecting the correct plural form.

If you’re dealing with a legacy application, or you don’t need the power offeredby the ICU message formatting, CakePHP also provides the sprintf formatter:

  1. return Package('sprintf', 'fallback_domain', $messages);

The messages to be translated will be passed to the sprintf() function forinterpolating the variables:

  1. __('Hello, my name is %s and I am %d years old', 'José', 29);

It is possible to set the default formatter for all translators created byCakePHP before they are used for the first time. This does not include manuallycreated translators using the setTranslator() and config() methods:

  1. I18n::defaultFormatter('sprintf');

Localizing Dates and Numbers

When outputting Dates and Numbers in your application, you will often need thatthey are formatted according to the preferred format for the country or regionthat you wish your page to be displayed.

In order to change how dates and numbers are displayed you just need to changethe current locale setting and use the right classes:

  1. use Cake\I18n\I18n;
  2. use Cake\I18n\Time;
  3. use Cake\I18n\Number;
  4.  
  5. // Prior to 3.5 use I18n::locale()
  6. I18n::setLocale('fr-FR');
  7.  
  8. $date = new Time('2015-04-05 23:00:00');
  9.  
  10. echo $date; // Displays 05/04/2015 23:00
  11.  
  12. echo Number::format(524.23); // Displays 524,23

Make sure you read the Date & Time and Numbersections to learn more about formatting options.

By default dates returned for the ORM results use the Cake\I18n\Time class,so displaying them directly in you application will be affected by changing thecurrent locale.

Parsing Localized Datetime Data

When accepting localized data from the request, it is nice to accept datetimeinformation in a user’s localized format. In a controller, orDispatcher Filters you can configure the Date, Time, andDateTime types to parse localized formats:

  1. use Cake\Database\Type;
  2.  
  3. // Enable default locale format parsing.
  4. Type::build('datetime')->useLocaleParser();
  5.  
  6. // Configure a custom datetime format parser format.
  7. Type::build('datetime')->useLocaleParser()->setLocaleFormat('dd-M-y');
  8.  
  9. // You can also use IntlDateFormatter constants.
  10. Type::build('datetime')->useLocaleParser()
  11. ->setLocaleFormat([IntlDateFormatter::SHORT, -1]);

The default parsing format is the same as the default string format.

Automatically Choosing the Locale Based on Request Data

By using the LocaleSelectorFilter in your application, CakePHP willautomatically set the locale based on the current user:

  1. // in src/Application.php
  2. use Cake\I18n\Middleware\LocaleSelectorMiddleware;
  3.  
  4. // Update the middleware function, adding the new middleware
  5. public function middleware($middleware)
  6. {
  7. // Add middleware and set the valid locales
  8. $middleware->add(new LocaleSelectorMiddleware(['en_US', 'fr_FR']));
  9. }
  10.  
  11. // Prior to 3.3.0, use the DispatchFilter
  12. // in config/bootstrap.php
  13. DispatcherFactory::add('LocaleSelector');
  14.  
  15. // Restrict the locales to only en_US, fr_FR
  16. DispatcherFactory::add('LocaleSelector', ['locales' => ['en_US', 'fr_FR']]);

The LocaleSelectorFilter will use the Accept-Language header toautomatically set the user’s preferred locale. You can use the locale listoption to restrict which locales will automatically be used.