I built some the following i18n function which is called several times when rendering view :
function e_($text)
{
$t = Translate::Instance();
vprintf($t->_($text), array_slice(func_get_args(), 1)); // outputs translated text
}
Currently, I get the instance of the Translate singleton Class inside the function.
I’ve read that dependency injection should be used instead.
But If I do use dependency injection, I will have to pass the Translate object each time into the function, right ?
This would became :
<?php e_('my text', $this->Translate);
and not simply <?php e_('my text'); ?>
Well I’d like to avoid that.
The way you use the
e_function is actually using an alias. That’s fine as long as you can live with it. You don’t need to use a singleton to implement an alias:When setting up the view layer, set the dependency:
In application context, set the global variable
$translate. This will allow you to move away from the singleton (which are liars), and you actually only need a global variable.Additionally it allows you to test views with the
e_alias against different translation implementations.The downside is that you need to manage a list of all these special global variables, like you need to maintain for the global functions like
e_.See as well this answer to the Getting
$thisinside function question.