Sometimes in our Zend Framework 3 multi-language application, we could need to access to Zend Translator component directly from Controllers. For example, when we have to translate a string to return in a JsonModel.
So, let’s see how to write a very simple Controller Plugin that will help us to save a lot of code (and time).
Following explanation will assume we just have at least a Skeleton ZF3 Application with working Zend Translator component.
First of all, we have to write our plugin that will take Zend Translator object in constructor and will wrap its translate() method. So let’s add following file module/Application/src/Controller/Plugin/TranslatePlugin.php:
|
|
Now, we need a Factory class to initialize our plugin and inject in it the Zend Translator component. That class will be placed in module/Application/src/Controller/Plugin/Factory/TranslatorPluginFactory.php and will be something like:
|
|
Finally, we have to configure ZF3 application to load plugin by adding following lines to module/Application/config/module.config.php file:
|
|
At this point, we can easily invoke our new plugin from each controller in application. For example we can do as following:
|
|
See also
- How to setup Docker container with legacy PHP 5.6 and Xdebug
- Split, reduce and convert PDF to JPEG using PHP ImageMagick
- Quickly setup HTTPS on PHP Apache2 Docker container with self-signed SSL certificate
- Building ZF3 composed pages using Nesting View Models and Forward Controller Plugin
- How to inject Zend Service Manager in ZF3 Controllers