3

I would like to offer my web site in several languages.

Witch of these two practices will be the best ?

Practice 1:

  • Create a php file for each lang (fr.php, en.php).
  • In each language file proceed by reference: $TEXT01 = 'Hello'; $TEXT02 = 'Goodbye';
  • Call the var in the page like this: <?php echo $TEXT01; ?> Marie.
  • Do I need to create ini files (https://stackoverflow.com/a/8636984/3678005) ?

Practice 2:

  • Create only one big function translator with an array for each text I need to translate.
  • Call the function in the page like this: <?php echo translator('Hello', 'en'); ?> Marie.

My questions:

  • Witch solution will be the fastest in terms of resources?
  • Witch solution will be the safest ?
  • Do you have another solution, if my two solutions are not optimal.

Thanks.

Community
  • 1
  • 1
user3678005
  • 55
  • 1
  • 5

2 Answers2

1

One fast way to do it would be to use an in-memory database.

Maybe first build your data files, exemple :


en_US.csv

hello_customer;Hello dear customer;
special_price;Special Price;

fr_FR.csv

hello_customer;Bonjour cher client;
special_price;Prix spécial;

...

Then install and configure redis (key / value in memory database).

Get the extension (for instance for php : https://code.google.com/p/phpredis/)

Now build a script to populate your redis database. Maybe something along these lines:

<?php
$csv_path = 'path/to/csv/files';

function redis_import($f_name){
    $handle = @fopen($f_name, "r");
    $redis = new Redis();

    $lang = explode('.', basename($f_name))[0];

    if ($handle) {
        $redis->connect('127.0.0.1', 6379);

        while (($buffer = fgets($handle, 4096)) !== false) {
            list($key, $value) = explode(';', trim($buffer));
            $redis->set($lang.'.'.$key, $val);
        }
        if (!feof($handle)) {
            echo "Erreur: fgets() a échoué\n";
        }
        fclose($handle);
    }

}

if ($handle = opendir($csv_path)) {
    while (false !== ($entry = readdir($handle))) {
        if (!is_dir($entry)) {
            redis_import($csv_path.PATH_SEPARATOR.$entry);
        }
    }
    closedir($handle);
}

So whenever the csv files are modified, launch this script to populate the database.

Then you'll need a function in your script to fetch language data.

You could use sessions to store user language. Assuming you used $_SESSION['user.lang'] to do so, you could craft something like this :

function __translate($key){
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    $translation =  $redis->get($_SESSION['user.lang'] . $key);
    $redis->close();
    return $translation;
}

This solution is very fast there are just memory accesses, and still with the usage of csv files the real database is safe, and easily human accessible.

Loïc
  • 11,804
  • 1
  • 31
  • 49
-1

Check out template engines like Smarty, they offer that functionality with included caching: http://www.smarty.net/

sibi
  • 39
  • 6