簡體   English   中英

遺留項目中的 Symfony 翻譯組件

[英]Symfony translation component in a legacy project

最近我在做一個非常大的項目,代碼主要是用 PHP 編寫的。 我正要重構一些代碼。 在我開始重構之前,我決定先編寫一些單元測試,以確保不會破壞任何東西(盡管無論如何這可能會發生......)。 在我嘗試設置 PHPUnit 時,我意識到我將要測試的代碼充滿了在全局命名空間中注冊的函數。 我決定暫時忽略這一點,並在此過程中考慮模擬這些全局函數的解決方案。

由於該項目在某些地方使用 PSR-4 而在其他地方沒有命名空間,因此很難繞過這些緊密耦合的全局函數。

我思考解決方案的時間越長,我就越意識到我需要將這些全局函數重寫為更面向對象的方式。 我對現有的第三方庫進行了一些研究,以替換這些全局函數提供的功能。

這些全局功能之一是某種翻譯服務。 我的想法是用 Symfony 的 Translation 組件替換它。 我必須克服的主要問題是使這項服務全球可訪問。 我想出了將它實現為單例的想法。 這只是作為 Symfony 的 Translation 組件返回 Translator 實例的包裝器。 我可以在整個代碼中從任何地方輕松訪問它,到目前為止我想不出更好的主意。

我不相信這是要走的路,所以我非常需要其他建議和想法。 所以我的問題是:

如何在缺乏一致命名空間的非 Symfony 項目中全局訪問 Symfony Translation 組件而不會產生太多開銷?

   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);
    }

然后像這樣使用它:

\App\Translation\Translate::getInstance()->trans('msg');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM