0

I'm building a multilingual site, and would like to store the language phrases in database.

This is my language table:

CREATE TABLE `language` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `key` varchar(100) DEFAULT NULL,
  `value` varchar(150) DEFAULT NULL,
  `type` varchar(50) DEFAULT NULL,
  `abr` varchar(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

key field stores the phrase key, while the value is the actual pharase

The function below is part of Language class:

public static function getPhrases()
{   
    $sql  = "SELECT * FROM language ORDER BY type";
    $data = $db->fetch($sql);

    $vals = array();
    foreach($data as $k => $row) 
    {
        $vals[] = $row->key;
    }

    return $vals;
}

I would like to be able to call language phrase like:

Language::HELLO, which would print "Hello"

in the above HELLO is the key, while Hello is the phrase needs to be printed.

msturdy
  • 10,479
  • 11
  • 41
  • 52
user3176519
  • 393
  • 1
  • 9
  • 16
  • 3
    I don't see a question here. But I think it would make more sense to have one table with all the languages as fields, and use the text in your native language as the key. – developerwjk Mar 11 '14 at 20:18
  • If you're simply looking for a multilingual website, using an established system like gettext which is made for this purpose would be a much better idea. – deceze Mar 11 '14 at 20:20
  • Good discussion of the main points here: http://stackoverflow.com/questions/2806886/most-efficient-approach-for-multilingual-php-website?rq=1 – msturdy Mar 11 '14 at 20:22
  • PHP doesn't support the magic `__get()` method for static properties so you can't do `Language::HELLO` because the `HELLO` must be dynamic. An instance would work though, e.g. `$lang->HELLO`. – MrCode Mar 11 '14 at 20:24
  • @MrCode I see, thanks for pointing out. I will just stick to text files instead. – user3176519 Mar 11 '14 at 20:28

1 Answers1

0
class Language {

    private $phrases;

    public function __construct($phrases = array()){
        $this->phrases = $phrases;
    }


    /**
    * Dynamically create getters for phrases
    * @param $name string
    */
    public function __get($name) {
        if (array_key_exists($name, $this->phrases)) {
            return $this->phrases[key];
        }
    }

    /**
    * Load language from database
    */
    public static function getLangauge(){   
        $sql  = "SELECT * FROM language ORDER BY type";
        $data = $db->fetch($sql);

        $vals = array();
        foreach($data as $k => $row) 
        {
            $vals[] = $row->key;
        }

        return new self($vals);
    }

}

$foolang = new Language(array('foo' => 'bar'));
echo $foolang->foo;
// bar
max
  • 96,212
  • 14
  • 104
  • 165
  • Allthough you should really have a look at the [symfony translation component](http://symfony.com/doc/current/components/translation/introduction.html) – max Mar 11 '14 at 20:39