PHP code example of monkeyscloud / monkeyslegion-i18n
1. Go to this page and download the library: Download monkeyscloud/monkeyslegion-i18n library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
monkeyscloud / monkeyslegion-i18n example snippets
// Explicit count forms
// "{0} No items|{1} One item|[2,*] :count items"
echo $translator->choice('messages.items', 0); // → "No items"
echo $translator->choice('messages.items', 1); // → "One item"
echo $translator->choice('messages.items', 42); // → "42 items"
// Range forms
// "[0,3] A few|[4,10] Several|[11,*] Many"
echo $translator->choice('messages.range', 2); // → "A few"
echo $translator->choice('messages.range', 7); // → "Several"
echo $translator->choice('messages.range', 50); // → "Many"
// Simple pipe-delimited (singular|plural)
// "apple|apples"
echo $translator->choice('messages.fruit', 1); // → "apple"
echo $translator->choice('messages.fruit', 5); // → "apples"
// With additional replacements
echo $translator->choice('messages.items', 3, ['color' => 'red']);
// "{0} No :color items|{1} One :color item|[2,*] :count :color items"
// → "3 red items"
// Register a namespace
$translator->addNamespace('billing', '/path/to/billing/lang');
$translator->addLoader(new FileLoader('/path/to/billing/lang'));
// Use namespace::group.key format
echo $translator->trans('billing::invoices.title');
// → Loads from /path/to/billing/lang/{locale}/invoices.json
$translator = new Translator('fr', 'en');
// If 'fr' translation missing, falls back to 'en'
echo $translator->trans('messages.welcome');
// French translation exists → "Bienvenue!"
echo $translator->trans('messages.rare_key');
// French missing, English fallback → "Rare English Value"
use MonkeysLegion\I18n\Loaders\FileLoader;
$loader = new FileLoader('/path/to/lang');
// Loads from /path/to/lang/{locale}/{group}.json
$messages = $loader->load('en', 'messages');
// Add namespace path
$loader->addNamespace('billing', '/path/to/billing/lang');
// Security features:
// ✅ Path traversal prevention (realpath validation)
// ✅ Null byte injection prevention
// ✅ Max file size limit (2MB)
// ✅ JSON_THROW_ON_ERROR on all json_decode
// ✅ Symlink resolution and validation
use MonkeysLegion\I18n\Loaders\DatabaseLoader;
// Works with any PDO connection — auto-detects driver
$loader = new DatabaseLoader($pdo, 'translations');
$messages = $loader->load('en', 'messages');
// Stack with FileLoader (DB translations override file translations)
$translator = new Translator('en', 'en');
$translator->addLoader(new FileLoader('/path/to/lang')); // Base
$translator->addLoader($loader); // Override
// Or use TranslatorFactory (recommended)
$translator = TranslatorFactory::create([
'path' => '/path/to/lang',
'pdo' => $pdo, // Enables DatabaseLoader automatically
]);
// Security features:
// ✅ Table name validated against regex pattern
// ✅ All queries use parameterized statements
// ✅ Cross-database UPSERT (ON CONFLICT / ON DUPLICATE KEY)
// ✅ Readonly PDO property
use MonkeysLegion\I18n\Loaders\CacheLoader;
$cached = new CacheLoader(
loader: $fileLoader,
cache: $psr16Cache,
ttl: 3600,
prefix: 'i18n',
);
// Features:
// ✅ TTL jitter (±10%) to prevent thundering herd
// ✅ Selective cache invalidation
// ✅ Flush all cached translations
$cached->forget('en', 'messages'); // Clear specific group
$cached->flush(); // Clear all
use MonkeysLegion\I18n\Loaders\CompiledLoader;
$compiled = new CompiledLoader(
sourceLoader: $fileLoader,
compilePath: '/var/cache/i18n',
);
// Compile all translations for a locale
$compiled->compile('en', '/path/to/lang');
// → Creates /var/cache/i18n/en.compiled.php
// Check if compiled cache is fresh
if (!$compiled->isFresh('en', '/path/to/lang')) {
$compiled->compile('en', '/path/to/lang');
}
// Invalidate
$compiled->invalidate('en');
// Atomic writes via temp file + rename
// Auto opcache invalidation
use MonkeysLegion\I18n\Loaders\MlcLoader;
$loader = new MlcLoader('/path/to/lang');
$messages = $loader->load('en', 'messages');
// Loads from /path/to/lang/en/messages.mlc
use MonkeysLegion\I18n\Middleware\LocaleMiddleware;
$middleware = new LocaleMiddleware(
manager: $localeManager,
translator: $translator,
setSession: true,
setCookie: true,
cookieTtl: 31536000, // 1 year
);
// Security features:
// ✅ SameSite=Lax on cookies
// ✅ HttpOnly flag
// ✅ Secure flag when HTTPS
// ✅ headers_sent() guard
use MonkeysLegion\I18n\Middleware\LocaleUrlMiddleware;
// /es/products → sets locale to "es"
$middleware = new LocaleUrlMiddleware($manager, $translator, segment: 0);
use MonkeysLegion\I18n\Middleware\LocaleRedirectMiddleware;
// /products → 302 → /en/products
$middleware = new LocaleRedirectMiddleware($manager, segment: 0);
// No exit() call — returns redirect response array
// ✅ headers_sent() guard
use MonkeysLegion\I18n\Enum\PluralCategory;
// ICU plural categories
PluralCategory::Zero; // "zero"
PluralCategory::One; // "one"
PluralCategory::Two; // "two"
PluralCategory::Few; // "few"
PluralCategory::Many; // "many"
PluralCategory::Other; // "other"
PluralCategory::Other->isDefault(); // → true
PluralCategory::ordered(); // Ordered list
// Get plural category for a count in a locale
$pluralizer = new Pluralizer();
$cat = $pluralizer->getCategoryForCount(5, 'en');
// → PluralCategory::Other
$cat = $pluralizer->getCategoryForCount(2, 'ar');
// → PluralCategory::Two
use MonkeysLegion\I18n\Attribute\Translatable;
class Product
{
#[Translatable(group: 'products', keyPrefix: 'title')]
public string $title;
#[Translatable(group: 'products', keyPrefix: 'description', fallbackToValue: true)]
public string $description;
}
use MonkeysLegion\I18n\Attribute\Locale;
class ProductController
{
public function index(#[Locale] string $locale): Response
{
// $locale is auto-populated from the detected locale
}
}
use MonkeysLegion\I18n\Event\LocaleChangedEvent;
// Immutable event (readonly class)
$translator->setEventDispatcher(function (LocaleChangedEvent $event): void {
echo $event->previousLocale; // → "en"
echo $event->newLocale; // → "es"
// Update user preferences, reconfigure formatters, etc.
});
use MonkeysLegion\I18n\Template\I18nDirectives;
$directives = new I18nDirectives($translator);
// Register all directives
foreach ($directives->getDirectives() as $name => $handler) {
$engine->directive($name, $handler);
}
// DatabaseLoader validates table names
new DatabaseLoader($pdo, 'DROP TABLE users; --'); // ❌ InvalidArgumentException
// All queries use parameterized statements
// Enable auto-escaping in MessageFormatter
$formatter = new MessageFormatter(autoEscape: true);
// All :param replacements are HTML-escaped via htmlspecialchars()
// Pre-load all groups at boot time
$translator->warmUp('en', ['messages', 'validation', 'auth', 'errors']);
// Locale-to-rule mapping is a const array (PHP 8.4)
// Zero overhead — compiled into opcache
private const array LOCALE_RULES = [
'pl' => 'polish',
'ru' => 'russian',
// ...
];
diff
// v1: All middleware in single file
- // src/Middleware/LocaleMiddleware.php contained 3 classes
// v2: One class per file
+ src/Middleware/LocaleMiddleware.php
+ src/Middleware/LocaleUrlMiddleware.php
+ src/Middleware/LocaleRedirectMiddleware.php
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.