JustinK101 Posted April 17, 2008 Share Posted April 17, 2008 I wrote a nice class which pulls all my language related strings/text from my database and stores eveything into an array. I am trying to figure out how to implement it properly using object oriented programming though. The Lanuage class is only instanciated ONCE on the first page index.php and that's it. The page index.php loads up all the text from the database and fills the array using the class member method add($k, $v). The loading and filling of the class variable $lang_array is done by calling add($k, $v) and should ONLY be executed on the index.php page ONCE. Then the entire instance of the class gets shoved into a session called language. From then on, on all pages should be able read from the class, but never again call the constructor or add($k, $v) method. So something like: $_SESSION['language']->get("welcome_text") should get me a text string like: "Welcome To My Project..." I am thinking I need a singleton class? Maybe static or abstract? Thanks. Here is what I have so far in terms of the class: <?php class Language { private $lang_array; public function Language($culture) { $this->lang_array = array(); $sql = "SELECT key, value FROM languages WHERE culture = '" . $culture . "' ORDER BY key ASC"; $result = mysql_query($sql) or trigger_error(mysql_error(), E_USER_ERROR); while($row = mysql_fetch_assoc($result)) { add($row['key'], $row['value']); } } private function add($k, $v) { $this->lang_array[$k] = $v; } public function get($k) { return ($this->lang_array[$k]); } } ?> So I guess the key is, you should only be able to instanciate one object of Language and never call add($k, $v) outside of the constructor. Link to comment https://forums.phpfreaks.com/topic/101489-writing-language-class/ Share on other sites More sharing options...
JustinK101 Posted April 17, 2008 Author Share Posted April 17, 2008 How is this looking? Using a singleton class. <?php class Language { private static $instance; private $lang_array; private function Language() {} public static function getInstance() { if(self::$instance == null) { self::$instance = new self; } return (self::$instance); } public function load($culture) { $this->lang_array = array(); $sql = "SELECT key, value FROM languages WHERE culture = '" . $culture . "' ORDER BY key ASC"; $result = mysql_query($sql) or trigger_error(mysql_error(), E_USER_ERROR); while($row = mysql_fetch_assoc($result)) { add($row['key'], $row['value']); } } private function add($k, $v) { $this->lang_array[$k] = $v; } public function get($k) { return ($this->lang_array[$k]); } } ?> USAGE: Language::getInstance()->load("us_en"); Humm, but how do I store this in a session so I can call get() on all my other pages? Link to comment https://forums.phpfreaks.com/topic/101489-writing-language-class/#findComment-519142 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.