The LanguageManager
class in JiFramework is designed to handle multi-language support within your application. It allows you to load, manage, and retrieve translation strings based on the user's selected language. The class supports language selection via URL parameters or cookies, and it can handle placeholders within translation strings for dynamic content.
By leveraging the LanguageManager
, you can easily internationalize your application, making it accessible to a broader audience by providing translations in multiple languages.
Usage:
use JIFramework\Core\App\App;
// Initialize the App
$app = new App();
// Get the instance
$languageManager = $app->languageManager;
OR
use JIFramework\Core\Language\LanguageManager;
// Get the instance
$languageManager = new LanguageManager();
Explanation:
- Checks if multi-language support is enabled (
MULTI_LANG
). - Automatically detects available languages by scanning the language directory for JSON files.
- Determines the current language based on the method specified (
MULTI_LANG_METHOD
). - Loads the language file for the current language.
- Throws an exception if multi-language support is disabled.
Before using the LanguageManager
, you need to configure the multi-language settings in your Config
class.
Configuration Options:
class Config {
// Enable or disable multi-language support
const MULTI_LANG = true;
// Method to determine language ('url' or 'cookie')
const MULTI_LANG_METHOD = 'url';
// Default language code (e.g., 'en')
const MULTI_LANG_DEFAULT_LANG = 'en';
// Key used in URL or cookie to store language preference
const MULTI_LANG_KEY = 'lang';
// Path to the language files directory
const MULTI_LANG_DIR = __DIR__ . '/../Languages/';
}
Explanation:
- MULTI_LANG (
bool
): Enables or disables multi-language support. - MULTI_LANG_METHOD (
string
): Determines how the language preference is stored: 'url'
: Language is specified via a URL parameter (e.g.,?lang=en
).'cookie'
: Language is stored in a cookie.- MULTI_LANG_DEFAULT_LANG (
string
): The default language code used when no preference is specified. - MULTI_LANG_KEY (
string
): The key used in the URL parameter or cookie to store the language code. - MULTI_LANG_DIR (
string
): The path to the directory containing language JSON files.
It's easy to add new languages to your application. Simply create a new JSON file for the language and place it in the language directory specified by MULTI_LANG_DIR
. The LanguageManager
will automatically detect and load any new languages added.
Mandatory Keys in Language Files:
Each language file must include the following mandatory keys:
- "langCode" (
string
): The language code (e.g.,'en'
,'fr'
,'es'
). - "langName" (
string
): The display name of the language (e.g.,'English'
,'Français'
,'Español'
). - "isRTL" (
bool
): Indicates whether the language is right-to-left (true
) or left-to-right (false
).
Example:
To add Spanish language support:
Create a new file named es.json in the language directory.
Include the mandatory keys and your translation strings:
{
"langCode": "es",
"langName": "Español",
"isRTL": false,
"welcome_message": "¡Bienvenido a nuestro sitio web!",
"greeting": "Hola, {name}!",
"farewell": "¡Adiós!"
}
The LanguageManager
will automatically detect the new language the next time it's initialized.
Method: setLanguage(string $lang): bool
Description: Changes the current language to the specified language code.
Parameters:
- $lang (
string
): The language code to switch to (e.g.,'en'
,'fr'
).
Returns: bool
indicating whether the language was successfully changed.
Usage:
// Change language to French
$languageManager->setLanguage('fr');
Explanation:
- Validates if the provided language code is available.
- Depending on the method (
'url'
or'cookie'
), it either redirects the user with the new language parameter or sets a cookie. - Reloads the language strings for the new language.
- Returns
true
if the language was successfully changed;false
otherwise.
Method: getAvailableLanguages(): array
Description: Retrieves the list of available languages.
Parameters: None
Returns:
An array of available languages, each containing:
- langCode (
string
): The language code. - langName (
string
): The display name of the language. - isRTL (
bool
): Indicates if the language is right-to-left.
Usage:
$languages = $languageManager->getAvailableLanguages();
foreach ($languages as $language) {
echo $language['langName'] . ' (' . $language['langCode'] . ')
';
}
Explanation:
- Automatically detects available languages by scanning the language directory for JSON files with the mandatory keys.
- Parses each language file to extract language information.
- Returns an array of languages available for selection.
Method: getCurrentLanguageCode(): string
Description: Gets the current language code being used.
Parameters: None
Returns: A string representing the current language code.
Usage:
$currentLang = $languageManager->getCurrentLanguageCode();
echo 'Current language: ' . $currentLang;
Explanation:
- Returns the language code determined during initialization or after a language change.
Method: translate(string $key, array $placeholders = []): string
Description: Retrieves a translated string based on the provided key and replaces any placeholders with provided values.
Parameters:
- $key (
string
): The translation key to look up. - $placeholders (
array
, optional): An associative array of placeholders and their replacement values.
Returns: The translated string with placeholders replaced, or the key itself if no translation is found.
Usage:
/* Simple translation */
echo $languageManager->translate('welcome_message');
/* Translation with placeholders */
// Translation string in JSON:
// "welcome_user": "Welcome, {name}! You have {count} new messages."
echo $languageManager->translate('welcome_user', [
'name' => 'Alice',
'count' => 5,
]);
// Output: "Welcome, Alice! You have 5 new messages."
Explanation:
- Looks up the translation string for the given key in the current language.
- If placeholders are provided, replaces
{placeholder}
in the translation string with the corresponding values. - If the key is not found in the current language, attempts to load it from the default language.
- If still not found, returns the key enclosed in
{key}
.
Method: getCurrentLanguageInfo(): ?array
Description: Retrieves information about the current language, including code, name, and directionality.
Parameters: None
Returns: An associative array containing:
- langCode (
string
): The language code. - langName (
string
): The display name of the language. - isRTL (
bool
): Indicates if the language is right-to-left.
Returns null
if the current language is not available.
Usage:
$langInfo = $languageManager->getCurrentLanguageInfo();
if ($langInfo) {
echo 'Language: ' . $langInfo['langName'];
echo $langInfo['isRTL'] ? ' (RTL)' : ' (LTR)';
}
Explanation:
- Provides detailed information about the current language, which can be useful for adjusting UI elements based on language directionality.
Method: isCurrentLanguageRTL(): bool
Description: Determines if the current language is right-to-left.
Parameters: None
Returns: bool
indicating whether the current language is RTL.
Usage:
if ($languageManager->isCurrentLanguageRTL()) {
// Adjust layout for RTL
echo '';
}
Explanation:
- Checks the
isRTL
property of the current language. - Useful for applying RTL styles or adjusting UI components.