Multi-lingual Support

The component Phalcon\Translate aids in creating multilingual applications. Applications using this component, display content in different languages, based on the user’s chosen language supported by the application.

Adapters

This component makes use of adapters to read translation messages from different sources in a unified way.

AdapterDescription
Phalcon\Translate\Adapter\NativeArrayUses PHP arrays to store the messages. This is the best option in terms of performance.

Factory

Loads Translate Adapter class using adapter option

  1. <?php
  2. use Phalcon\Translate\Factory;
  3. $options = [
  4. 'locale' => 'de_DE.UTF-8',
  5. 'defaultDomain' => 'translations',
  6. 'directory' => '/path/to/application/locales',
  7. 'category' => LC_MESSAGES,
  8. 'adapter' => 'gettext',
  9. ];
  10. $translate = Factory::load($options);

Component Usage

Translation strings are stored in files. The structure of these files could vary depending of the adapter used. Phalcon gives you the freedom to organize your translation strings. A simple structure could be:

  1. app/messages/en.php
  2. app/messages/es.php
  3. app/messages/fr.php
  4. app/messages/zh.php

Each file contains an array of the translations in a key/value manner. For each translation file, keys are unique. The same array is used in different files, where keys remain the same and values contain the translated strings depending on each language.

  1. <?php
  2. // app/messages/en.php
  3. $messages = [
  4. 'hi' => 'Hello',
  5. 'bye' => 'Good Bye',
  6. 'hi-name' => 'Hello %name%',
  7. 'song' => 'This song is %song%',
  8. ];
  1. <?php
  2. // app/messages/fr.php
  3. $messages = [
  4. 'hi' => 'Bonjour',
  5. 'bye' => 'Au revoir',
  6. 'hi-name' => 'Bonjour %name%',
  7. 'song' => 'La chanson est %song%',
  8. ];

Implementing the translation mechanism in your application is trivial but depends on how you wish to implement it. You can use an automatic detection of the language from the user’s browser or you can provide a settings page where the user can select their language.

A simple way of detecting the user’s language is to parse the $_SERVER['HTTP_ACCEPT_LANGUAGE'] contents, or if you wish, access it directly by calling $this->request->getBestLanguage() from an action/controller:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. use Phalcon\Translate\Adapter\NativeArray;
  4. class UserController extends Controller
  5. {
  6. protected function getTranslation()
  7. {
  8. // Ask browser what is the best language
  9. $language = $this->request->getBestLanguage();
  10. $messages = [];
  11. $translationFile = 'app/messages/' . $language . '.php';
  12. // Check if we have a translation file for that lang
  13. if (file_exists($translationFile)) {
  14. require $translationFile;
  15. } else {
  16. // Fallback to some default
  17. require 'app/messages/en.php';
  18. }
  19. // Return a translation object $messages comes from the require
  20. // statement above
  21. return new NativeArray(
  22. [
  23. 'content' => $messages,
  24. ]
  25. );
  26. }
  27. public function indexAction()
  28. {
  29. $this->view->name = 'Mike';
  30. $this->view->t = $this->getTranslation();
  31. }
  32. }

The _getTranslation() method is available for all actions that require translations. The $t variable is passed to the views, and with it,we can translate strings in that layer:

  1. <!-- welcome -->
  2. <!-- String: hi => 'Hello' -->
  3. <p><?php echo $t->_('hi'), ' ', $name; ?></p>

The () method is returning the translated string based on the index passed. Some strings need to incorporate placeholders forcalculated data i.e. Hello %name%. These placeholders can be replaced with passed parameters in the () method. The passed parameters are in the form of a key/value array, where the key matches the placeholder name and the value is the actual data to be replaced:

  1. <!-- welcome -->
  2. <!-- String: hi-name => 'Hello %name%' -->
  3. <p><?php echo $t->_('hi-name', ['name' => $name]); ?></p>

Some applications implement multilingual on the URL such as http://www.mozilla.org/**es-ES**/firefox/. Phalcon can implement this by using a Router.

The implementation above is helpful but it requires a base controller to implement the _getTranslation() and return the Phalcon\Translate\Adapter\NativeArray component. Additionaly the component needs to be set in the view as seen above in the $t variable.

You can always wrap this functionality in its own class and register that class in the DI container:

  1. <?php
  2. use Phalcon\Mvc\User\Component;
  3. use Phalcon\Translate\Adapter\NativeArray;
  4. class Locale extends Component
  5. {
  6. public function getTranslator()
  7. {
  8. // Ask browser what is the best language
  9. $language = $this->request->getBestLanguage();
  10. /**
  11. * We are using JSON based files for storing translations.
  12. * You will need to check if the file exists!
  13. */
  14. $translations = json_decode(
  15. file_get_contents('app/messages/' . $language . '.json'),
  16. true
  17. );
  18. // Return a translation object $messages comes from the require
  19. // statement above
  20. return new NativeArray(
  21. [
  22. 'content' => $translations,
  23. ]
  24. );
  25. }
  26. }

This way you can use the component in controllers:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class MyController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. $name = 'Mike';
  8. $text = $this->locale->_('hi-name', ['name' => $name]);
  9. $this->view->text = $text;
  10. }
  11. }

or in a view directly

  1. <?php echo $locale->_('hi-name', ['name' => 'Mike']);

Implementing your own adapters

The Phalcon\Translate\AdapterInterface interface must be implemented in order to create your own translate adapters or extend the existing ones:

  1. <?php
  2. use Phalcon\Translate\AdapterInterface;
  3. class MyTranslateAdapter implements AdapterInterface
  4. {
  5. /**
  6. * Adapter constructor
  7. *
  8. * @param array $options
  9. */
  10. public function __construct(array $options);
  11. /**
  12. * @param string $translateKey
  13. * @param array|null $placeholders
  14. * @return string
  15. */
  16. public function t($translateKey, $placeholders = null);
  17. /**
  18. * Returns the translation string of the given key
  19. *
  20. * @param string $translateKey
  21. * @param array $placeholders
  22. * @return string
  23. */
  24. public function _(string $translateKey, $placeholders = null): string;
  25. /**
  26. * Returns the translation related to the given key
  27. *
  28. * @param string $index
  29. * @param array $placeholders
  30. * @return string
  31. */
  32. public function query(string $index, $placeholders = null): string;
  33. /**
  34. * Check whether is defined a translation key in the internal array
  35. *
  36. * @param string $index
  37. * @return bool
  38. */
  39. public function exists(string $index): bool;
  40. }

There are more adapters available for this components in the Phalcon Incubator