[Solar-talk] locale strings + replacements
Rodrigo Moraes
rodrigo.moraes at gmail.com
Thu Nov 16 07:40:18 PST 2006
Hi,
Antti told me this idea some time ago: Solar::locale + replacements. I
don't remember of seeing he posting about this, so here it is. Let's
say we have a silly locale string like:
'TEXT_MONKEYS_INVASION' => 'The %2$s contains %1$d monkeys.';
Then we can call the GetText helper passing replacements for the string:
$data = array(7, 'house');
echo $this->getText('TEXT_MONKEYS_INVASION', 1, $data)
...which will output:
The house contains 7 monkeys.
As you see, the house is full of monkeys. I mean, this is useful for
building locale strings that are easily adapted to different language
grammars.
And all it needs is a basic change - add a parameter "replacements" to
the locale helpers and functions:
Solar_View_Helper_GetText
--------------------------------------
public function getText($key, $num = 1, $replacements = null)
{
return $this->_view->escape($this->_view->getTextRaw($key,
$num, $replacements));
}
Solar_View_Helper_GetTextRaw
--------------------------------------
public function getTextRaw($key, $num = 1, $replacements = null)
{
// [snip]
// get the translation
return Solar::locale($class, $key, $num, $replacements);
}
Solar
--------------------------------------
public static function locale($class, $key, $num = 1, $replacements = null)
{
// [snip]
// return the number-appropriate version of the
// translated key, if multiple values exist.
if ($num != 1 && ! empty($string[1])) {
if(!$replacements) {
return $string[1];
} else {
return vsprintf($string[1], $replacements);
}
} else {
if(!$replacements) {
return $string[0];
} else {
return vsprintf($string[0], $replacements);
}
}
}
Simple, huh? And it is so useful. Maybe you will find the strings ugly
with the sprintf specifications, but this is the simplest PHP
implementation, I think. Different implementations (using str_replace
or other functions) can be done on the helper level. Solar should
provide a simple way to use string replacements.
Do you think this would be flexible enough? Do you think something
like this should be implemented in the Solar::locale() level or only
in helpers?
But anyway, here's (more or less) Antti's idea (I hope; don't kill me,
Antti :-).
rodrigo
---------------------------------------------------------------------
Solar has now a Community Wiki: solarphp.org
---------------------------------------------------------------------
Join the #solarphp IRC channel on freenode.org
---------------------------------------------------------------------
More information about the solar-talk
mailing list