Zend Translate Adapter for DB (MySql)
Zend Framework offers multiple adapters for translations. Among them is not an adapter for database translating. Here is how-to :)
I need to point out that there are other possibilities that offer much more flexibility than database and are designed to handle translations (one of them that is widely used and I recommend is Gettext for which Zend already has native adapter). Use this one if you are not sure!
Advantages for storing translations in database
- you can program custom translation tool
- more flexible
Disadvantages for storing translations in database
- you have to program custom translation tools (gettext has tools like PO Edit)
- performance should be slower that with other tools like gettext (although I did not test this)
Zend Translate Adapter for Database
As I said before Zend is offering different adapters for translating. They are located under library/Zend/Translate/Adapter. When writing a custom code it usually pays off to review the code already written. If we open few translate adapters and look at the code it's quite obvious that it does two basic things:
- opens translation storage
- parses translations in one array for later use in translate object
With this knowledge we can write our own adapter that works with database.
Note: ALWAYS extend the code in your own library NEVER modify the core!
Prepare model that reads translations from db
Firstly we create a model that fetches our translations from database. For simplicity sake I used the same approach as gettext uses (msgid, msgstring).
/** * Database model for photos */ class Application_Model_Translation extends Zend_Db_Table_Abstract { /** * The default table name */ protected $_name = 'translation'; /** * The primary key column. * * @var string */ protected $_primary = 'translation_id'; /** * Get list of locale translations * @param locale */ public function getListByLocale($locale) { $select = $this->_db->select() ->where('locale = ?', $locale ); return $this->_db->fetchAll($select); } }
Prepare translation helper
/** Zend_Locale */ require_once 'Zend/Locale.php'; /** Zend_Translate_Adapter */ require_once 'Zend/Translate/Adapter.php'; class App_Translate_Adapter_Db extends Zend_Translate_Adapter { /** * override the default Zend_Translate_Adapter function with our own */ { //get translations from db $db = Zend_Registry::get('db'); $translations = $translation->getListByLocale( Zend_Registry::get('Zend_Locale')->__toString() ); foreach ($translations as $trans) { $this->_data[$locale][ $trans['msgid'] ] = $trans['msgstring']; } return $this->_data; } }
Put it all together
You'll probably want to initialize translation object with this adapter at bootstrap.
| Next > |
|---|