Translation from DB ZF2

115 Views Asked by At

I have database with two fields - translation.name and translation.value.

It is possible to create custom translator in ZF2, like standard $this->translate("SomeKey"); using translation from database? Please, tell me, how to implement it in my project?

1

There are 1 best solutions below

3
Sam On

What you are looking for is nothing but a simple ViewHelper which replaces the ViewHelper that is currently assigned to $this->translate().

Basically you need to add this to your config:

'view_helpers' => [
    'factories' => [
        'translate' => 'My\View\Helper\Factory\TranslateFactory'
    ]
]

Then you need to write your Factory class implementing the FactoryInterface. This Factory will then create your actual ViewHelper. You need to do this via a Factory because your ViewHelper will have the database-access as a dependency. Furthermore you need to inject the current locale used to your ViewHelper.

This brings me to the last point: What kind of translation table is that? Any translation table should support multiple languages, either add a language key or don't use the database at all.

And ultimately: be sure to CACHE ALL THE THINGS! If a key has been translated once, it's unlikely to change anytime, so have it cached and don't make needless DB calls in the future! Be sure to have your cache running ONE FILE only so you don't make 5000 I/O Calls either.