English 中文(简体)
Phalcon - Multi-Lingual Support
  • 时间:2024-09-17

Phalcon - Multi-Lingual Support


Previous Page Next Page  

Phalcon includes a component PhalconTranslate which provides multi-pngual 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.

Example

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 Engpsh 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.

en.php

<?php  

// app/messages/en.php 

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

fr.php

<?php 

// 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 apppcation, create a UserController which will take parameters as to which file should be used for translation.

<?php 

use PhalconTranslateAdapterNativeArray; 

class UserController extends PhalconMvcController {  
   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,]); 
   }  
   pubpc 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 Engpsh.

Step 3 − The associated code view demoappviewsUserindex.volt will include the following code −

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

Index

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 Advertisements