Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translation facility in Phalcon

Does Phalcon provide any facility for multilingual web sites?

What is best practice for developing an MVC phalcon based site? How should I implement view layer?

like image 536
Handsome Nerd Avatar asked Oct 20 '12 15:10

Handsome Nerd


3 Answers

This sample application (https://github.com/phalcon/php-site) implements translation using Phalcon.

like image 176
twistedxtra Avatar answered Oct 22 '22 01:10

twistedxtra


Phalcon does not offer I18n functionality. There is a PECL extension that offers this kind of functionality, called intl (see manual).

However, if you are mostly interested in presenting the website in different languages, you can use the

\Phalcon\Translate\Adapter\NativeArray 

component. This component uses an array of key/values that contain the language aware strings. For instance you can use this in your config:

$trans_config = array(
                    'en' => array(
                        'bye'       => 'Good Bye',
                        'song-key'  => 'This song is %song% (%artist%)',
                    ),
                    'es' => array(
                        'bye'       => 'Adiós',
                        'song-key'  => 'La canción es %song% (%artist%)',
                    ),
                );

A test to demonstrate the above usage is:

public function testVariableSubstitutionTwoEnglish()
{
    $language   = $trans_config['en'];
    $params     = array('content' => $language);
    $translator = new \Phalcon\Translate\Adapter\NativeArray($params);

    $vars     = array(
        'song'   => 'Dust in the wind',
        'artist' => 'Kansas',
    );
    $expected = 'This song is Dust in the wind (Kansas)';
    $actual   = $translator->_('song-key', $vars);

    $this->assertEquals(
        $expected,
        $actual,
        'Translator does not translate English correctly - many parameters'
    );
}

The above just shows how you can get translated messages with placeholder variables. To simply get a string in a different language, you just call the _() on the translator with the relevant key and no variables passed.

EDIT In the view you can work as you like. You can set variables that are displayed in the view layer or pass the translating object and perform the translation there. Up to you.

HTH

like image 2
Nikolaos Dimopoulos Avatar answered Oct 22 '22 03:10

Nikolaos Dimopoulos


I think the best solution is to use Phalcon Gettext Adapter. The most important advantage of Gettext is handling plurals.

like image 2
IH2 Avatar answered Oct 22 '22 03:10

IH2