-->

Best way to implement multilanguage in PHP

2019-02-21 04:27发布

问题:

I have multilanguage PHP system with over 30 languages. Each definition is made with define():

define('LN_loader_alt', 'Loading...');

And there is over 400 definitions.

I made a little comparison and created abstract class Lang with over 400 constants and these constant are instead of define() of course, example:

abstract class Lang{
    const LN_loader_alt = 'Loading';
    ...
}

Next I required both files and called 1 define and 1 const from class Lang. Next I made analysis with webgrind and results surprised for me:

1) requiring file with 400 defines() took over 70% times of executing script 2) Using abstract class with constant is much faster than define()

I'd like to share with You this analysis and ask You: is it optimal and smart to rewrite my system from "define()" multilanguage to "abstract class with constant" multilanguage? Or maybe has it any disadvantages?

回答1:

My spontaneous guess would be that define() is a runtime function call with a certain overhead, but a class definition and its constants are parsed at compile time. Hence the difference.

Having said that, both solutions are terrible. I18n is a solved problem that does not need to be reinvented yet again. The biggest problem in i18n is the workflow, and you need tools that support that workflow. That workflow is:

  • markup of translatable strings in the source
  • extraction of said strings into a source-code neutral format
  • translation of those strings into various languages
  • all of the above asynchronously with parallel changes happening done by separate people, and keeping everything synched up between all your languages

There are tools that already do all this, the most established one being gettext. Use it (or something similar), don't use constants.

See:

  • http://www.gnu.org/software/gettext/
  • http://pology.nedohodnik.net//doc/user/en_US/ch-poformat.html


回答2:

I believe that the ideal is to use helpers and perform the translation only on demand.

Example:

<?php
// View.php
//...
echo translate('Hello World');

The function search for the corresponding of expression in the current language dictionary or just echo "Hello World" if not found one translation.

I consider good you rewrite your system, since 400 items is not so much so.