Recently I was working on a very large project, with code mainly written in PHP. I was about to refactor some code. Before I started refactoring I decided to write some unit tests first to have some confidence about not breaking anything (although this would probably happen anyway...). At the time I was trying to set up PHPUnit I realised the code I was about to test was full of function registered in the global namespace. I decided to ignore this for the time being and think about a solution for mocking these global functions along the way.
Due to the fact that this project is using PSR-4 in some places and no namespacing in other places made it very hard to circumvent these thightly coupled global functions.
The longer I was thinking about a solution the more I realised I needed to rewrite these global functions into are more object-oriented way. I did some research about existing third-party libraries to replace the functionality these global functions provided.
One of these global functions is some kind of a translation service. My idea is to replace this with the Symfony's Translation component. The main problem I have to overcome is to make this service globally accessible. I came up with the idea of implementing it as a Singleton. This would just act as a wrapper around Symfony's Translation component returning the Translator instance. I could easily access it from anywhere throughout the code and so far I could not come up with a better idea.
I am not convinced if this is the way to go, so I am very much in the need of other suggestions and ideas. So my question is:
How can I make the Symfony Translation component globally accessible in a non-Symfony project lacking consistent namespacing without generating too much overhead?
namespace App\Translation;
use Symfony\Component\Translation as Translation;
class Translate extends Translation\Translator implements TranslateInterface
{
private static $singleton;
public static function getInstance($locale = null): Translate
{
if (static::$singleton === null) {
static::$singleton = new static($locale ?: 'de');
}
return static::$singleton;
}
public function __construct($locale, Translation\Formatter\MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false)
{
$this->addLoader('json', new Translation\Loader\JsonFileLoader());
$this->addResource('json', 'translations\messages.de.json', 'de');
parent::__construct($locale, $formatter, $cacheDir, $debug);
}
And then use it like this:
\App\Translation\Translate::getInstance()->trans('msg');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.