0

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?

doydoy44
  • 5,720
  • 4
  • 29
  • 45
Walllter
  • 342
  • 8
  • 19

1 Answers1

1

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.

Sam
  • 16,435
  • 6
  • 55
  • 89
  • Thank you for the answer! Maybe, do you have some examples, please? I novice in ZF2, and do not understand this =( – Walllter Mar 26 '14 at 10:07
  • 1
    Well @Walllter, google about ZF2 ViewHelper and learn about what a ViewHelper is. Then start by replacing the default ViewHelper with something that simply returns a string. And then learn about Factories within ZF2. There's loads of information out there :) – Sam Mar 26 '14 at 10:34
  • Hello Sam. Could you please help me? I have a problem with this, and I created a new topic at http://stackoverflow.com/questions/22824423/translations-from-db-in-zf2 – Walllter Apr 03 '14 at 05:50