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

What are the minimum user permissions required to install a Windows service?

windows service rights

What are the minimum user permissions required to install a Windows service?

ExpressJS server is not setting correct headers

node.js express frontend backend

I have created an ExpressJS server on port 8080 that will be receiving requests from another webapp running on port 8889. I've set the appropriate headers, but the browser console still gives me...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.