【发布时间】:2015-11-13 18:36:33
【问题描述】:
我正在制作自己的框架,并且有一个翻译器类在整个应用程序的几个地方使用。
我担心翻译器类有一个构造函数,其中包含翻译所需的所有文件,这意味着每个具有翻译器的对象都可能多次包含这些文件。
这是一个翻译器类的例子。
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,不如把它放在一个全局变量中?
$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];
}
【问题讨论】:
-
除非它是一个Translator,否则任何东西都不应该扩展Translator类。所谓的 Translator 也不应该扩展 Application。
-
了解对象组合。
-
另外,您的课程看起来做得太多了。因为如果他们都需要访问所说的翻译,他们有太多的责任
-
“到目前为止,其他类扩展了翻译器类以访问翻译方法。” => 其他类是否也希望将路由器扩展为可以访问路由方法,控制器可以访问视图相关的方法,and,and,and?但这行不通,因为您不能扩展多个类。你考虑过这个吗?
-
@AlexanderWeihmayer:要明确一点:扩展翻译器的想法是可怕的和误导的。在用火杀死它之前,您当然应该了解原因,但这是另一个话题。在这里,我试图提供其他更直接的实际原因,说明为什么这不起作用。我仍然认为不会。但即使是这样,那也只是我的旁注。 永远不要这样做。此错误也称为“汽车扩展引擎”,搜索该错误可能会得到更好的结果。
标签: php oop global-variables global extends