Created
June 1, 2015 20:57
-
-
Save luckyshot/3161357ba3e5fcf50e77 to your computer and use it in GitHub Desktop.
Simple Multilanguage functionality
This file contains hidden or 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 | |
define('LANGUAGES_PATH', 'languages/'); | |
define('DEFAULT_LANGUAGE', 'en'); | |
define('LANGUAGE_COOKIE_TIME', 1314000 ); // 3600 * 365 = 1314000; (1 year) | |
define('COOKIE_DOMAIN', '.xaviesteve.com'); | |
/* | |
Usage: | |
$dict = new Dictionary; | |
$dict->_( 'Click here' ); | |
$dict->_( 'Hello %1', array('Xavi') ); | |
languages/en.php: | |
<?php | |
$dictionary = array( | |
'ln' => 'en', | |
'Click here' => 'Click here', | |
); | |
*/ | |
Class Dictionary { | |
private $dictionary = []; | |
// Stores and returns the language | |
function __construct( $ln = false ) | |
{ | |
// if language has been specified then just return that | |
if ( $ln ) | |
{ | |
$this->load( $ln ); | |
} | |
else | |
{ | |
$this->load( $this->detect() ); | |
} | |
return $this->dictionary; | |
} | |
// Find out the language | |
private function detect() | |
{ | |
// GET / POST parameter | |
if ( isset( $_REQUEST['ln'] ) AND $this->is_valid_ln( $_REQUEST['ln'] ) ) | |
{ | |
$_COOKIE['ln'] = $_GET['ln']; | |
setcookie( 'ln', $_GET['ln'], time() + LANGUAGE_COOKIE_TIME, '/', COOKIE_DOMAIN ); | |
$ln = $_GET['ln']; | |
} | |
// Cookie | |
else if ( isset( $_COOKIE['ln'] ) AND $this->is_valid_ln( $_COOKIE['ln'] ) ) | |
{ | |
$ln = $_COOKIE['ln']; | |
} | |
// If browser-specified | |
else if ( isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) AND $this->is_valid_ln( strpos( $_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2 ) ) ) | |
{ | |
$ln = explode( ",", $_SERVER['HTTP_ACCEPT_LANGUAGE'] ); | |
} | |
else | |
{ | |
$ln = DEFAULT_LANGUAGE; | |
} | |
return $ln; | |
} | |
private function load( $ln = false ) | |
{ | |
if ( $this->is_valid_ln( $ln ) ) | |
{ | |
require LANGUAGES_PATH . $ln . '.php'; | |
$this->dictionary = $dictionary; | |
} | |
else | |
{ | |
require LANGUAGES_PATH . DEFAULT_LANGUAGE . '.php'; | |
$this->dictionary = $dictionary; | |
} | |
return $this->dictionary; | |
} | |
private function is_valid_ln( $ln = false ) | |
{ | |
return file_exists( LANGUAGES_PATH . $ln . '.php' ); | |
} | |
public function _( $string, $vars = array() ) | |
{ | |
if ( isset( $this->dictionary ) AND isset( $this->dictionary[ $string ] ) ) | |
{ | |
$return = $this->dictionary[ $string ]; | |
} | |
else | |
{ | |
$return = $string; | |
} | |
$i = 1; | |
foreach ($vars as $var) { | |
$return = str_replace( '%' . $i, $vars[ $i-1 ], $return ); | |
$i++; | |
} | |
return $return; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment