Skip to content

Instantly share code, notes, and snippets.

@renan
Created October 24, 2014 11:25
Show Gist options
  • Save renan/a7f080829ee68c786418 to your computer and use it in GitHub Desktop.
Save renan/a7f080829ee68c786418 to your computer and use it in GitHub Desktop.
Translator
<?php
use \MessageFormatter;
class Translator {
// This should be loading from a file. Eg: .po files (http://en.wikipedia.org/wiki/Gettext)
protected static $messages = [
'pt' => [
'Hello world' => 'Olá mundo',
],
'nl' => [
'Hello world' => 'Hello wereld',
],
];
// Probably changes once during a request
protected static $locale = 'en';
public static function setLocale($locale) {
static::$locale = $locale;
}
public static function translate($message, array $args = []) {
// Use the localized message if found
if (!empty(static::$messages[static::$locale][$message])) {
$message = static::$messages[static::$locale][$message];
}
return MessageFormatter::formatMessage(static::$locale, $message, $args);
}
}
function sayHello() {
return Translator::translate('Hello world');
}
// Default = english
var_dump(sayHello());
// Portuguese
Translator::setLocale('pt');
var_dump(sayHello());
// Italian, fallback to original
Translator::setLocale('it');
var_dump(sayHello());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment