2015-11-13 43 views
1

我正在製作自己的框架,並在整個應用程序的幾個地方使用翻譯器類。PHP翻譯類 - 最佳實踐意見

我的問題是,翻譯器類有一個構造函數,它包含所有必需的翻譯文件,這意味着每個有翻譯器的對象可能會多次包含這些文件。

這是翻譯器類的一個例子。

class Translator{ 
    protected $translations; 

    public function __construct(){ 
     $this->translations[] = include $this->language . ".php"; //General texts for a language 
     $this->translations[] = include $this->language . "-" . $this->controller . ".php"; //General texts for a controller 
     $this->translations[] = include $this->language . "-" . $this->controller . "-" . $this->action . ".php"; //Specific texts for an action 
    } 

    public function translate($key){ 
     return $this->translations[$key]; 
    } 

} 

這將是如何通過擴展來實現。 在閱讀了關於對象組合的內容之後,似乎非常沮喪地採用這種方式。見http://www.cs.utah.edu/~germain/PPS/Topics/oop.html

class View extends Translator{ 
    ... 
} 

與我瞭解的對象組成這是我的理解應該如何進行。錯誤?如果不是這樣,這會產生翻譯器類的多個實例,並且如果我沒有弄錯,仍然存在多個包含的問題。

class View{ 
    protected $translator; 

    public function __construct(){ 
     $this->translator = new Translator(); 
    } 

    ... 
} 

而是創建一個新的翻譯,怎麼樣在一個全局變量堅持呢?

$translator = new Translator(); 

class View{ 
    protected $translator; 

    public function __construct(){ 
     global $translator 
     $this->translator = $translator; 
    } 

    ... 
} 

最新理念,以公共職能,而不是一類

$translations = //Include the language array files like in the translator class 

function translate($key){ 
    global $translations; 
    return $translations[$key]; 
} 
+1

除非是*是*譯者,否則不應該擴展翻譯器類。翻譯者也不應該擴展某種應用程序。 – PeeHaa

+1

瞭解物體組成。 – PeeHaa

+1

另外它看起來像你的班級做得太多了。因爲他們有太多的責任,如果他們都需要訪問說翻譯 – PeeHaa

回答

0

編輯

我發現靜態類是更容易使用。基本上,您不需要在需要時獲取翻譯器的實例,您可以通過使用靜態類在整個應用程序中使用它。我認爲使用靜態類存在性能問題,但顯然,新的PHP版本並非如此。

檢查了這一點,以獲得有關如何製造和使用靜態類的想法: Is it possible to create static classes in PHP (like in C#)?

OLD

正如mentionned由喬恩,我結束了艇員選拔的方法是爲一個單獨的類翻譯。基本上,翻譯器實例僅創建一次,並且每個地方都要求翻譯器的實例獲取相同的實例。確保在使用之前瞭解這種方法的缺點。

這裏是如何做到這一點 Creating the Singleton design pattern in PHP5

快速演示

final class Translator{ 
    protected $translations; 

    public static function getInstance(){ 
     static $inst = null; 
     if ($inst === null){ 
      $inst = new Translator(); 
     } 
     return $inst; 
    } 

    private function __construct(){ //Private constructor so nobody else can instance it 
     ...//Look at translator class in question 
    } 
} 

要得到翻譯的情況下一個很好的例子,稱這在你需要它。

$translator = Transaltor::getInstance();