GitHub

Localization and Translation

The TinyMVC framework provides a comprehensive translation system for multilingual applications, supporting text translation, pluralization, and variable substitution.

Translation Files

Translation files are stored in /resources/languages/ directory, organized by language codes (e.g., en.php, bd.php). Each file returns an associative array of translations.

<?php
// resources/languages/en.php
return [
    'hello' => 'Hello!',
    'welcome' => 'Welcome, %s!',
    'apple_count' => ['%d apple', '%d apples'],
    'profile_updated' => 'Your profile was updated on %s'
];

Basic Usage

Use the __() helper function for translations:

// Simple translation
echo __('hello'); // Outputs: Hello!

// With variable substitution
echo __('welcome', 'John'); // Outputs: Welcome, John!

// With HTML escaping
echo __e('welcome', '<John>'); // Outputs: Welcome, &lt;John&gt;!

Pluralization

For plural forms, provide an array with singular and plural versions in your translation file:

// In your language file
'apple_count' => ['%d apple', '%d apples']

Usage:

echo __('apple_count', 1); // Outputs: 1 apple
echo __('apple_count', 5); // Outputs: 5 apples

Advanced Variable Substitution

You can use multiple placeholders and provide different arguments for singular and plural forms:

// In your language file
'user_action' => [
    '%s has %d message', 
    '%s has %d messages'
]

Usage:

echo __('user_action', 1, ['John', 1]); 
// Outputs: John has 1 message

echo __('user_action', 2, ['Jane', 2]); 
// Outputs: Jane has 2 messages

Adding Translation Files

You can add additional translation files in a service provider:

public function register()
{
    $translator = $this->app->get(Translator::class);
    $translator->addLanguageFile(lang_dir('admin/notice/fr.php'));
}

Configuration

The default language is set in your configuration:

// In your env.php or config file
'lang' => 'en',
'lang_dir' => '/resources/languages'

Translator Class Methods

Method Description Example
translate() Main translation method $translator->translate('hello', 'John')
addLanguageFile() Adds a language file to load $translator->addLanguageFile('path/to/file.php')
mergeTranslatedTexts() Merges additional translations $translator->mergeTranslatedTexts(['new' => 'New text'])
setTranslatedTexts() Replaces all translations $translator->setTranslatedTexts([])

Best Practices

  • Use consistent keys across all language files
  • Keep translations organized by module/feature when possible
  • Use __e() for any user-facing text that will be rendered in HTML
  • For complex pluralization rules, consider implementing a custom solution
  • Load only necessary language files for better performance
Note: The translator automatically loads the default language file on initialization and can lazy-load additional files when translations are requested.