FastSitePHP\Lang\I18N

Internationalization (I18N) API

This class provides an easy to use API for sites and apps that need to support multiple languages.

[i18n] is spelled "Internationalisation" in British English. [i18n] is an acronym/numeronym that represents ("i" + 18 characters + "n"). The difference is US English uses "z" while British English uses an "s" in the spelling of the word.

Using this class requires a global [\FastSitePHP\Application] object to be assigned to the variable [$app].

Source Code

GitHub

رمز المثال

Handle Language Translations for a Site or App

// FastSitePHP provides an easy to use Internationalization (i18n) API for
// sites and apps that need to support multiple languages. The code is
// structured but minimal in size so if you have different translation needs
// you can simply copy and modify the class.

// Translations are saved as JSON files in the same directory using the name
// format of “{name}.{lang}.json”. An optional main file named “_.{lang}.json”
// if found will loaded first. The main file “_” is useful for storing key
// translations such as menus, page headers, page footers, etc.

// An optional fallback language can be specified so that missing translations
// default to another language. This allows partially translated sites to use
// this API.

// Since the API is simple and easy to use there are only two functions to call:
// [langFile()] and [textFile()].

// Example Files:
//     _.en.json
//     _.es.json
//     header.en.json
//     header.es.json
//     about.en.json

// Using this code the above files will be loaded in the order listed.
$app->config['I18N_DIR'] = __DIR__ . '/i18n';
$app->config['I18N_FALLBACK_LANG'] = 'en';

\FastSitePHP\Lang\I18N::langFile('header', 'es');
\FastSitePHP\Lang\I18N::langFile('about', 'es');

// Typical usage is allowed for an app to load a language
// file based on the Requested URL:
$app->get('/:lang/about', function($lang) {
    \FastSitePHP\Lang\I18N::langFile('about', $lang);
});

// [setup()] can be called for each request to make sure
// that a language file is always loaded for template rendering when
// [$app->render()] is called.
//
// This is useful if your site uses PHP or other templates for rendering
// and expects the [i18n] default file to always be available. For example
// an unexpected error or call to [$app->pageNotFound()] can trigger a
// template to be rendered.
\FastSitePHP\Lang\I18N::setup($app);

// Loaded translations are set to the app property ($app->locals['i18n'])
// so that they can be used with template rendering and the calling page.

// When using a URL format of [https://www.example.com/{lang}/{pages}]
// and a fallback language the user will be re-directed to the same page
// with the fallback language if the specified language doesn't exist.

// When [langFile()] is called and the language is verified as valid
// it is set to the app property ($app->lang).

// The other I18N function [textFile()] simply takes a full file path
// containing the text '{lang}' along with the selected language and then loads
// the file or if it doesn't exist, the matching file for the fallback language.
$file_path = $app->config['I18N_DIR'] . '/test-{lang}.txt';
$content = \FastSitePHP\Lang\I18N::textFile($file_path, $app->lang);

// Use [getUserDefaultLang()] to get the default language for the user based
// on the 'Accept-Language' Request Header and available languages for the site.
//
// This is useful to provide custom content for the user or to redirect to the
// user's language when they access the default URL.
//
// Requires config values I18N_DIR and I18N_FALLBACK_LANG.
$default_lang = \FastSitePHP\Lang\I18N::getUserDefaultLang();

Properties

Name Data Type Default Description
loaded_files array
(Static)
[] Array of file paths loaded when calling [langFile()] in the order that they were loaded. This property is primarily used for Unit Testing however it can also be useful to help so unexpected translations in case multiple files are loaded.
opened_text_files array
(Static)
[] Array of file paths opened when calling [textFile()] in the order that they were loaded. Just like [$loaded_files] this property is primarily used for Unit Testing.
redirect_on_missing_lang bool
(Static)
false The default behavior if using a fallback language and the language is not matched is to send a 404 response when calling [langFile()].

If this is set to [true] then the user will be redirected to the same page using the fallback language. For this feature to work the requested URL must have the language parameter after the host (example: "https://www.example.com/{lang}/{pages}").

Methods

langFile($file_name, $lang)

Static Function

This function read JSON files from a directory specified in the config setting ($app->config['I18N_DIR']) and then loaded translations are set to the app property ($app->locals['i18n']) so that they can be used with template rendering and from the calling page. When the language is verified as valid it is set to the app property ($app->lang).

All JSON files need to be in the same directory and have a format of [{name}.{lang}.json]. An optional main file named [_.{lang}.json] if found will first be loaded when this function is called.

A fallback language can be specified so that missing translations default to another language. This allows partially translated sites to use this API. Fallback language is set as config setting ($app->config['I18N_FALLBACK_LANG']).

If a fallback language is defined and the language specified is not matched and the requested url has a format of [https://www.example.com/{lang}/{pages}] then this function will redirect to the fallback language and end PHP processing.

The file specified as a parameter to this function (or optional fallback) is required to exist; if not an exception is thrown. This paramater is not intended to be a based on user input however the generated file name is validated for security in case an app sets the value based on user input.

Example Files:
    _.en.json
    _.es.json
    header.en.json
    header.es.json
    about.en.json

Example Code:
    // Assuming the files above exist they would be loaded
    // in the order shown above based on this code.
    $app->config['I18N_DIR'] = __DIR__ . '/i18n';
    $app->config['I18N_FALLBACK_LANG'] = 'en';
    I18N::langFile('header', 'es');
    I18N::langFile('about', 'es');

    // Typical usage is allow for an app to load a language
    // file based on the Requested URL:
    $app->get('/:lang/about', function($lang) {
        I18N::langFile('about', $lang);

textFile($file_path, $lang)

Static Function

Return the contents of a file based on the User's selected language.

Just like the function [langFile()] ths function uses a fallback language from the Application config settings to handle partially translated sites.

[$file_path] is a full file path requires the text '{lang}' anywhere in the file path. The '{lang}' value gets replaced wiht the user's selected language. This paramater is intended to be hard-coded by the app and users should not have the ability to input their own file paths as it would be a security risk.

The file is required to exist (either selected language or fallback language) otherwise an exception is thrown.

Example Code:
    // Config Option
    $app->config['I18N_FALLBACK_LANG'] = 'en';

    // Typical usage is allow for an app to load file content
    // based on the the User's Selected Language:
    $app->get('/:lang/sample-code', function($lang) {
        $file_path = __DIR__ . '/../app_data/files/sample-code-{lang}.txt'
        return I18N::textFile($file_path, $lang);

Returns: string

getUserDefaultLang()

Static Function

Return the default language for the user based on the 'Accept-Language' request header and available languages for the site.

This is useful to provide custom content for the user or to redirect to the user's language when they access the default URL.

Requires config values:
    $app->config['I18N_DIR']
    $app->config['I18N_FALLBACK_LANG']

Example usage:
    $app->redirect($app->rootUrl() . I18N::getUserDefaultLang() . '/');

Returns: string

hasLang($lang)

Static Function

Return true if the language is supported by the site. For a language to be supported it must include a '_.{lang}.json' file in the [I18N_DIR] directory.

Requires config value:
    $app->config['I18N_DIR']

Returns: bool

setup(Application $app)

Static Function

Static function that can be called for each request to make sure that a language file is always loaded for template rendering when [$app->render()] is called.

This is useful if your site uses PHP or other templates for rendering and expects the [i18n] default file to always be available. For example an unexpected error or call to [$app->pageNotFound()] can trigger a template to be rendered.