I am making my own framework and have a translator class that is used in a few places throughout the application.
My concern is that the translator class has a constructor that includes all the necessary files for translation which means that every object that has a translator includes these files possibly multiple times.
This is an example of the translator class.
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];
}
}
This would be how to do it by extending. After reading about object composition, this way seems to be strongly discouraged. See http://www.cs.utah.edu/~germain/PPS/Topics/oop.html
class View extends Translator{
...
}
With what I read about object composition this is how I understand how it should be made. Wrong? If not, this makes multiple instances of the translator class and still has the problem of multiple includes if I'm not mistaken.
class View{
protected $translator;
public function __construct(){
$this->translator = new Translator();
}
...
}
Instead of creating a new Translator, how about sticking it in a global variable?
$translator = new Translator();
class View{
protected $translator;
public function __construct(){
global $translator
$this->translator = $translator;
}
...
}
Last idea, with public functions instead of a class
$translations = //Include the language array files like in the translator class
function translate($key){
global $translations;
return $translations[$key];
}