Ways to avoid singleton when calling a object inside a global function?

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:

function e_($text)
    return $GLOBALS['e_alias']->alias(func_get_args());

When setting up the view layer, set the dependency:

$GLOBALS['e_alias'] = $translate;

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 $this inside function question.

Need Your Help

Submit multiple FORMS as 1 combined form?

javascript jquery forms twitter-bootstrap

I am using a jQuery plug-in to implement an accordion wizard based on bootstrap. http://sathomas.me/acc-wizard/#prerequisites

Like Box - Not displaying page feed

feed facebook-likebox

I'm a very basic programmer and previously added the like box to a website. At the time it displayed the facebook page feed in real-time and worked great. displaying the facebook page activity feed...