Phalcon - Multi-Lingual Support


Phalcon includes a component Phalcon\Translate which provides multi-lingual support and it is very helpful to create web pages, which gets translated in multiple languages.

It includes an adapter which helps in binding arrays and assists in reading translation messages.


Let us create an output with the help of Translate component in Phalcon, which will help to display the output as per the language suggested.

Step 1 − Phalcon gives freedom to every developer to organize translation strings. Consider keeping two different files namely: en.php (for English strings) and fr.php (for French strings).

The file will contain an array of key-value pair, where the keys are unique and values will differ as per the translation needed.



// app/messages/en.php 

$messagesContent = [ 
   "bye"     => "Good Bye", 
   "hi-name" => "Hello %name%", 
   "song"    => "Your favorite song is %song%", 



// app/messages/fr.php 

$messagesContent = [ 
   "bye"        => "Au revoir", 
   "hello-name" => "Bonjour %name%", 
   "song"       => "Votre chanson préférée est %song%", 

Step 2 − In an application, create a UserController which will take parameters as to which file should be used for translation.


use Phalcon\Translate\Adapter\NativeArray; 

class UserController extends \Phalcon\Mvc\Controller {  
   protected function getMessageTransalation() { 
      // Ask for the best language 
      // Display the output in desired language 
      require "en.php";   
      // Return a translation object 
      return new NativeArray( ["content" => $messagesContent,]); 
   public function indexAction() { 
      $this->view->name = "Radhika"; 
      $this->view->song= "Ton sourire m'ensorcelle Je suis fou de toi Le désir coule dans mes veines Guidé par ta voix"; 
      $this->view->t    = $this->getMessageTransalation(); 

For the default method, two parameters are taken, first is name and the second is the favorite song of the user. Later, the function getMessageTranslation is being called which returns the desired output.

For now, we want the output in English.

Step 3 − The associated code view demo\app\views\User\index.volt will include the following code −

<p><?php echo $t->_("hello-name", ["name" => $name]); ?></p> 
<p><?php echo $t->_("song", ["song" => $song]); ?></p> 


If we want the complete output to be displayed in French, we only need to change the file name.

require "fr.php"; 

Following is the output in French.

Output in French