CakePHP Internationalization

PHPz
Release: 2024-09-10 17:26:30
Original
514 people have browsed it

Like many other frameworks, CakePHP also supports Internationalization. We need to follow these steps to go from single language to multiple language.

Step 1

Create a separate locales directory resourceslocales.

Step 2

Create subdirectory for each language, under the directory srcLocale. The name of the subdirectory can be two letter ISO code of the language or full locale name like en_US, fr_FR etc.

Step 3

Create separate default.po file under each language subdirectory. This file contains entry in the form of msgid and msgstr, as shown in the following program.

msgid "msg"
msgstr "CakePHP Internationalization example."
Copy after login
Copy after login

Here, the msgid is the key which will be used in the View template file and msgstr is the value which stores the translation.

Step 4

In the View template file, we can use the above msgid, as shown below which will be translated based on the set value of locale.

<?php echo __('msg'); ?>
Copy after login

The default locale can be set in the config/app.php file by the following line.

'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US')
Copy after login

To change the local at runtime, we can use the following lines.

use Cake\I18n\I18n;
I18n::locale('de_DE');
Copy after login

Example

Make changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',
      ['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('locale',
      ['controller'=>'Localizations','action'=>'index']);
   $builder->fallbacks();
});
Copy after login

Create a LocalizationsController.php file at src/Controller/LocalizationsController.php. Copy the following code in the controller file.

src/Controller/LocalizationsController.php

<?php namespace App\Controller;
   use App\Controller\AppController;
   use Cake\I18n\I18n;
   class LocalizationsController extends AppController {
      public function index() {
         if($this->request->is('post')) {
            $locale = $this->request->getData('locale');
            I18n::setLocale($locale);
         }
      }
   }
?>
Copy after login

Create a locales directory at resourceslocales. Create 3 directories called en_US, fr_FR, de_DE under the locales directory. Create a file under each directory called default.po. Copy the following code in the respective file.

resources/locales/en_US/default.po

msgid "msg"
msgstr "CakePHP Internationalization example."
Copy after login
Copy after login

resources/locales/fr_FR/default.po

msgid "msg"
msgstr "Exemple CakePHP internationalisation."
Copy after login

resources/locales/de_DE/default.po

msgid "msg"
msgstr "CakePHP Internationalisierung Beispiel."
Copy after login

Create a directory Localizations at src/Template and under that directory, create a View file called index.php. Copy the following code in that file.

src/Template/Localizations/index.php

Form->create(NULL,array('url'=>'/locale'));
   echo $this->Form->radio("locale",
      [
         ['value'=>'en_US','text'=>'CakePHP Internationalization'],
         ['value'=>'de_DE','text'=>'German'],
         ['value'=>'fr_FR','text'=>'French'],
      ]
   );
   echo $this->Form->button('Change Language');
   echo $this->Form->end();
?>
<?php echo __('msg'); ?>
Copy after login

Execute the above example by visiting the following URL. http://localhost/cakephp4/locale

Output

Upon execution, you will receive the following output.

CakePHP Internationalization

Email

CakePHP provides Email class to manage email related functionalities. To use email functionality in any controller, we first need to load the Email class by writing the following line.

use Cake\Mailer\Email;
Copy after login

The Email class provides various useful methods which are described below.

Syntax
Syntax

From(string|array|null $email null, string|null $name null )

Parameters
  • String with email

  • Name

Returns

array|$this

Description

It specifies from which email address; the email will be sent

From(string|array|null $email null, string|null $name null )
Parameters
  • String with email
    Syntax

    To(string|array|null $emailnull, string|null $namenull)

    Parameters
    • String with email

    • Name

    Returns

    array|$this

    Description

    It specifies to whom the email will be sent

  • Name
Returns
Syntax

Send(string|array|null $contentnull)

Parameters
  • String with message or array with messages.

Returns array
Description

Send an email using the specified content, template and layout

array|$this
Description
It specifies from which email address; the email will be sent
Syntax

Subject(string|null $subjectnull)

Parameters
  • Subject string

Returns

array|$this

Description

Get/Set Subject

Syntax To(string|array|null $emailnull, string|null $namenull)
Parameters
  • String with email
  • Name
Returns array|$this
Description It specifies to whom the email will be sent
Syntax Send(string|array|null $contentnull)
Parameters
  • String with message or array with messages.
Returns array
Description Send an email using the specified content, template and layout
Syntax Subject(string|null $subjectnull)
Parameters
  • Subject string
Returns array|$this
Description Get/Set Subject
Syntax

Attachments(string|array|null $attachmentsnull)

Parameters
  • String with the filename or array with filenames

Returns

array|$this

Description

Add attachments to the email message

Syntax

Bcc(string|array|null $emailnull, string|null $namenull)

Parameters
  • String with email

  • Name

Returns

array|$this

Description

Bcc

Syntax

cc( string|array|null $emailnull , string|null $namenull )

Parameters
  • String with email

  • Name

Returns

array|$this

Description

Cc

Example

Make changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('/email',['controller'=>'Emails','action'=>'index']);
   $builder->fallbacks();
});
Copy after login

Create an EmailsController.php file at src/Controller/EmailsController.php. Copy the following code in the controller file.

src/Controller/EmailsController.php

<?php namespace App\Controller;
   use App\Controller\AppController;
   use Cake\Mailer\Email;
   class EmailsController extends AppController{
      public function index(){
         $email = new Email('default');
         $email->to('abc@gmail.com')
            ->subject('About')
            ->send('My message');
      }
   }
?>
Copy after login

Create a directory Emails at src/Template and under that directory, create a View file called index.php. Copy the following code in that file.

src/Template/Emails/index.php

Email Sent.
Copy after login

Before we send any email, we need to configure it. In the below screenshot, you can see that there are two transports, default and Gmail. We have used Gmail transport.

You need to replace the “GMAIL USERNAME” with your Gmail username and “APP PASSWORD” with your applications password. You need to turn on 2-step verification in Gmail and create a new APP password to send email.

config/app.php

Program App

Execute the above example by visiting the following URL − http://localhost/cakephp/email

Output

Upon execution, you will receive the following output.

Documents Api

The above is the detailed content of CakePHP Internationalization. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!