Categories
CakePHP Career Code Area PHP Tips and Tricks Tools and Technologies

Internationalization & Localization Application with CakePHP 3

CakePHP has one of the coolest features to make application Internationalization & Localization. It’s really easy to translate your application or website into multiple languages with CakePHP 3.  Let’s see it.

First of all, create a directory Locale inside PROJECT_ROOT/src

Create a subdirectory of each language (which language you want to translate your application) inside PROJECT_ROOT/src/Locale/. Subdirectory name can be anything (ex. english, french, etc), but prefer ISO code of the language (ex. en_US, fr_FR, bn_BN etc). So follow this tutorial and make your subdirectory name en_USfr_FR, and bn_BN

Create default.po file inside all subdirectories (en_USfr_FR, and bn_BN). And copy the following code in the respective file.

src/Locale/en_US/default.po

msgid "message"
msgstr "Hello World"

 

src/Locale/fr_FR/default.po

msgid "message"
msgstr "Bonjour le monde"

 

src/Locale/bn_BN/default.po

msgid "message"
msgstr "ওহে বিশ্ব"

Here msgid key of which will use inside the template (view files) and msgstr is the values which will gonna translate.

So now you have three different languages (en_USfr_FR, and bn_BN). and one key (message) which can be translated into these three languages.

Now use <?php echo __(‘message’); ?> in your view (any ctp file of your application).

Then open PROJECT_ROOT/config/app.php file and find

 'defaultLocale' => env('APP_DEFAULT_LOCALE', 'fr_FR')

and replace with your language.

But if you want to translate language in runtime then you can use it

use Cake\I18n\I18n;

I18n::locale('fr_FR');

I hope this article will help you to translate your application in multiple language.