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).

 

Prepare translation helper

Put it all together

You’ll probably want to initialize translation object with this adapter at bootstrap.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please prove me that you are not spamer :) * Time limit is exhausted. Please reload CAPTCHA.