我正在製作自己的框架,並在整個應用程序的幾個地方使用翻譯器類。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];
}
除非是*是*譯者,否則不應該擴展翻譯器類。翻譯者也不應該擴展某種應用程序。 – PeeHaa
瞭解物體組成。 – PeeHaa
另外它看起來像你的班級做得太多了。因爲他們有太多的責任,如果他們都需要訪問說翻譯 – PeeHaa