Created
October 24, 2014 11:25
-
-
Save renan/a7f080829ee68c786418 to your computer and use it in GitHub Desktop.
Translator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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