PHPTAL comes with a default gettext translation service, as shown in another section. For some reason you may prefer to implement your own service of translation.
The PHPTAL_TranslationService interface is here to serve your needs.
The usage of your service will be the same as the PHPTAL_GetTextTranslator.
$tpl->setTranslator($yourOwnTranslatorInstance);
Your implementation must define the following methods:
This method may be called by the template to change the current output language.
Its arguments are a list of possible languages (use func_get_args() to get the argument array). The first known language should be used by your service.
<?php
require_once 'PHPTAL/TranslationService.php';
class MyTranslator implements PHPTAL_TranslationService {
...
public function setLanguage(){
$langs = func_get_args();
foreach ($langs as $lang){
// if $lang known use it and stop the loop
$this->_currentLang = $lang;
return;
}
}
...
private $_currentLang;
}
?>
If you decided to store your translations into separate files, one for each application, for example, this method allows you to select the translation domain from your templates (i18n:domain).
<?php
require_once 'PHPTAL/TranslationService.php';
class MyTranslator implements PHPTAL_TranslationService {
...
public function useDomain($domain){
if (!array_key_exists($domain, $this->_domains)){
$file = "domains/$this->_currentLang/$domain.php";
$this->_domains[$domain] = include($file);
}
$this->_currentDomain = $this->_domains[$domain];
}
...
private $_currentDomain;
private $_domains = array();
}
?>
The above example is a possible translation solution where keys are stored in php files which return an associative array of key => translation.
This method matches i18n:name calls. It builds an interpolation context for later translate calls.
<?php
require_once 'PHPTAL/TranslationService.php';
class MyTranslator implements PHPTAL_TranslationService {
...
public function setVar($key, $value){
$this->_context[$key] = $value;
}
...
private $_context = array();
}
?>
The last and most important method to implement, it asks your service to translate the specified key for the currently selected language.
<?php
require_once 'PHPTAL/TranslationService.php';
class MyTranslator implements PHPTAL_TranslationService {
...
public function translate($key){
$value = $this->_currentDomain[$key];
// interpolate ${myvar} using context associative array
while (preg_match('/\${(.*?)\}/sm', $value, $m)){
list($src,$var) = $m;
if (!array_key_exists($var, $this->_context)){
$err = sprintf('Interpolation error, var "%s" not set',
$var);
throw new Exception($err);
}
$value = str_replace($src, $this->_context[$var], $value);
}
return $value;
}
...
}
?>