Skip to content

09. Support multiple languages

Dzyanis Sukhanitski edited this page Mar 13, 2024 · 7 revisions

Default language

You need to set at least one default language for your application. By default, in the framework config file the language set is English:

'default language' => 'en',
'supported languages' => array(
   "en" => "English"
),

You can override this setting in the application config file App/configs/app.config.php in accordance with your locale.

Configuring multiple languages

Step 1.

in the application config file App/configs/app.config.php you can add as many languages as your application needs. But at least one language must be set as a default:

'default language' => 'en',
'supported languages' => array(
   "en" => "English",
   "be" => "Беларуская мова"
),

or, simply:

'default language' => 'en',
'supported languages' => ['en', 'be],

Important: the language tag code must be set within any standard that matches the IETF BCP 47 (languages tags).

https://en.wikipedia.org/wiki/IETF_language_tag

https://www.w3schools.com/tags/ref_language_codes.asp

Step 2.

Add languages files into App/lang/ folder. The file name must match the language tag:

/App
   /lang
      /en.php
      /be.php     

The language file is a simple array with keys and values as language text:

<?php

return array(
    'title default' => 'Videna - PHP MVC Micro-Framework',
    'description default' => 'Videna - PHP MVC Micro-Framework',
);

Step 3.

In the view file, you can call the language string using the array $_

<?= $_['title default'] ?>

If you need to, you can get the value of the language string in the controller:

use Lang;
...
$str = Lang::get('title default');

Multiple languages logic

If the application config determines more than one supported language, the Videna framework tries to detect automatically which language is most suitable to proceed. Here are the priority levels:

  1. (Highest) value of language tag provided in the URL
  2. Value that set in cookies
  3. value that set in user settings
  4. (lowest) value of default language from config file

If the detected language is different from the default one, the default language array is loaded first and, next, merges with the detected language array.

Passing language tag in URL

To force language change via URL you need to provide in the router method the parameter {lang}, for example:

Route::view('/{lang}/', 'index.php')->where(['lang' => 'be|en']);

The router catches parameter {lang} and provides its value (language tag) to the application to verify if it exists in the supported languages array. If it is, the application language will be changed.

Getting language tag

In the view file, you can get the language tag:

<?= $app->lang ?>

In the controller, you can get the language tag:

use App;
...
$str = App::getLang();

Clone this wiki locally