my i18n Class ported to lava

Started on the old forum in October 2010 · view the original in the archive · old links redirect here

7 replies · 620 views · started 16 years ago · 1 min read

4 participants
CreativityKills Lead · 833 posts #1

I see many lava sites try to add multi languages, but i daresay they doin it in an old fashioned manner. So since ive been baking mG 2 (as demanded) i wrote a PHP 5 framework on which im baking mG 2. This is the i18n library i use. Note php 5 only.

Added after 8 minutes:

<?php (!defined('I18N_PATH')) AND die('Direct script access is forbidden.');
/**
 * i18n Class ported from Lypid PHP framework.
 *
 * @package  Lypid Core
 * @subpackage  mGiGS Core
 * @author  Neo Ighodaro
 * @copyright  (c) CreativityKills Networks
 */
class i18n {

// translations
public static $translations = array();

// active locale
public static $locale = 'en-us';

// singleton instance
public static $instance;

public static function instance()
{
if(i18n::$instance !== NULL)
return i18n::instance;

return i18n::instance = new i18n;
}

// set the locale
public function set_locale($locale = null)
{
i18n::$locale = $locale;

return i18n::$instance;
}

public function load()
{
if(isset(i18n::$translations[i18n::$locale]))
return i18n::$translations[i18n::$locale];

$path = I18N_PATH.i18n::$locale.'.php';

if(is_file($path) AND (is_readable($path))
{
$translations = array();

require $path;

return i18n::$translations[i18n::$locale] = $translations;
}
else
{
trigger_error('i18n file '.$path.' not found.', E_USER_WARNING);
return FALSE;
}
}

public static function gettext($line)
{
return isset(i18n::$translations[i18n::$locale][$line]) ? i18n::$translations[i18n::$locale][$line] : null;
}
}

function __($text, $vals = null)
{
return is_array($vals) ? strtr(i18n::gettext($text), $vals) : $text;
}
CreativityKills Lead · 833 posts #2

Completing it...

Added after 53 minutes:

Ok its a reeally scaled down version bt that shud be gud. Usage. In ur index file or whatever:

// file: ./index.php

// path to i18n folder
define('I18N_PATH', './i18n/');

// class library
require 'i18n.php';

// Load a locale 'en-us.php'
i18n::instance()->set_locale('en-us')->load();

// Outputs: Hello Neo welcome to mG
echo __('hello_user', array(':user:' => 'Neo', ':site:' => 'mG'));

// Load a locale 'my-leet.php'
i18n::instance()->set_locale('my-leet')->load();

// Outputs: H3ll0 Neo w3lc0m3 t0 mG
echo __('hello_user', array(':user:' => 'Neo', ':site:' => 'mG'));

sample locale file

// file: i18n/en-us.php
<?php (!defined('I18N_PATH')) and die('Direct script access is forbidden.');

$translations['hello_user'] = 'Hello :user: welcome to :site:';
$translations['Password'] = 'Password';

sample locale file

// file: i18n/my-leet.php
<?php (!defined('I18N_PATH')) and die('Direct script access is forbidden.');

$translations['hello_user'] = 'H3ll0 :user: w3lc0m3 t0 :site:';
$translations['Password'] = 'Pa55w0rd';
shakil420 Developer · 125 posts #3

MGIGs bro ur coding is very hard to uderstand .... nice work

amore Junior · 31 posts #5

yes mate u posting very valuble things.. but some are realy hard to understand.. appreciate if u expalin it simply . thanks @ CreativityKills

amylee Principal · 1,092 posts #6

exactly how i handle the multi language on my script

CreativityKills Lead · 833 posts #7

@amy...Knw what they say bout great minds.

@all...let me try to explain as much as i can. Though to understand this u must have basic knwledge of Object Oriented Programming. With the release of PHP5, its been incredibly easy creating powerful libraries using OOP. Anyway, to the class...

Added after 19 minutes:

In the "i18n.php" file, we create a CLASS that helps us handle i18n (internalization) by include()-ing a locale file which contains array of "key => value" sets, say "short key" => "full translation". Now in each of our locale files, the array "keys" should match, bt the value the key holds should vary according to translation. E.G:

// In en-us.php (english locale file) we have...
$translation['hello_user'] = 'Good day :user:';
$translation['goodbye'] = 'Goodbye';

// In fr-fr.php (french locale file) we have...
$translation['hello_user'] = 'Bonjour :user:';
$translation['goodbye'] = 'Au revoire';

Incase u didnt notice, the only fing changing, is the translation. The array key is should we say static. Now in each translation, u see sumting like ":user:" thats not translated, this is because we'll use php's strtr() function to replace those values, in whichever translation.

Added after 19 minutes:

U have to place all ur translation files in the same folder. Say a "/locales/" folder. Now to the class proper. We want the class to load locale files and store the translations in an array, to avoid double loading the file every time a translation is requested. That said, moving forward. We use the "static" keyword on variables to make sure the values stay static and nt reset everytime. Read more abt static, public, final, abstract, protected and private keywords on php.net.

The i18n class has 3 "public" & "static" properties.

/**
 * The current locale thats being used. Default is en-us.
 */
public static $locale = 'en-us';

/**
 * Internally caches ALL the translations immediately they are loaded.
 */
public static $translations = array();

/**
 * Stores an object instance.
 */
public static $instance;
CreativityKills Lead · 833 posts #8

In the "i18n.php" file, we create a CLASS that helps us handle i18n (internalization) by include()-ing a locale file which contains array of "key => value" sets, say "short key" => "full translation". Now in each of our locale files, the array "keys" should match, bt the value the key holds should vary according to translation. E.G:

// In en-us.php (english locale file) we have...
$translation['hello_user'] = 'Good day :user:';
$translation['goodbye'] = 'Goodbye';

// In fr-fr.php (french locale file) we have...
$translation['hello_user'] = 'Bonjour :user:';
$translation['goodbye'] = 'Au revoire';

Incase u didnt notice, the only fing changing, is the translation. The array key is should we say static. Now in each translation, u see sumting like ":user:" thats not translated, this is because we'll use php's strtr() function to replace those values, in whichever translation.

Added after 2 minutes:

The first method in the class is the instance method. Since its a "static" method, we dnt have to use the "new" keyword to access it. E.g if it wasnt static, we'd probably do this:

$i18n = new i18n;
$i18n->instance();

but its static so, we can do...

i18n::instance();

cool right? Anyways, in the instance method, we try to get ONE instance of the class, so we dnt instantiate the class, new, new, new everytime. With this method, we can save php memory, by using one method for each class call. Anyway... So to instantiate our i18n class we must do

i18n::instance();
// ...and not
$i18n = new i18n;

but to be sure you might want to add the following method to the class, before the instance method.

protected function __construct()
{
// Forces use of the instance method.
}

Added after 9 minutes:

Anyway moving on. We got the set_locale. All it does is change our source locale. E.g the default locale is "en-us" which means we get our translations from "/locales/en-us.php" bt when we do...

i18n::instance()->set_locale('fr-fr');

we tell the class that frm that point we want our new source of locale files is "locales/fr-fr.php" simple.

Added after 19 minutes:

Next is the load() method. It simply loads a locale file IF its not been loaded before.

i18n::instance()->set_locale('fr_fr')->load();

See how the methods are chained? Read about method chaining in php.net if it confuses u.

Added after 17 minutes:

Note that load() wil throw a custom catchable php error if d locale file is missing. Next the gettext(), gets a translation after load() has loaded it. We then specify a convenience function __() that isnt part of the class bt uses the class. So now we can do...to output french

i18n::instance()->set_locale('fr_fr')->load();
echo __('hello_user', array(':user:' => 'mobileGiGS'));

...and

i18n::instance()->set_locale('en_us')->load();
echo __('hello_user', array(':user:' => 'mobileGiGS'));

...to output english. The trick to using this is setting the preferred locale on top, like

i18n::instance()->set_locale('fr_fr')->load();

...then your contents text should be in the convenience function anywhere withing that script and its included files.

echo __('hello_user', array(':user:' => 'losers')).'<br/>';
echo __('goodbye');

Questions...?

Write your reply now; next you create a free account (or sign in) and it is posted right away. Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close