>  기사  >  백엔드 개발  >  CakePHP 국제화

CakePHP 국제화

PHPz
PHPz원래의
2024-09-10 17:26:30272검색

다른 많은 프레임워크와 마찬가지로 CakePHP도 국제화를 지원합니다. 단일 언어에서 다중 언어로 전환하려면 다음 단계를 따라야 합니다.

1단계

별도의 로케일 디렉토리 리소스로케일을 만듭니다.

2단계

srcLocale 디렉터리 아래에 각 언어에 대한 하위 디렉터리를 만듭니다. 하위 디렉토리의 이름은 언어의 두 글자 ISO 코드이거나 en_US, fr_FR 등과 같은 전체 로케일 이름일 수 있습니다.

3단계

각 언어 하위 디렉터리에 별도의 default.po 파일을 만듭니다. 이 파일에는 다음 프로그램과 같이 msgidmsgstr 형식의 항목이 포함되어 있습니다.

msgid "msg"
msgstr "CakePHP Internationalization example."

여기서 msgid는 보기 템플릿 파일에서 사용될 키이고 msgstr은 번역을 저장하는 값입니다.

4단계

View 템플릿 파일에서 위의 msgid를 아래와 같이 사용할 수 있으며 이는 설정된 로케일 값에 따라 번역됩니다.

<?php echo __('msg'); ?>

기본 로캘은 config/app.php 파일에서 다음 줄을 사용하여 설정할 수 있습니다.

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

런타임에 로컬을 변경하려면 다음 줄을 사용할 수 있습니다.

use Cake\I18n\I18n;
I18n::locale('de_DE');

다음 프로그램과 같이 config/routes.php 파일을 변경합니다.

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();
});

src/Controller/LocalizationsController.php에서 LocalizationsController.php 파일을 생성합니다. 컨트롤러 파일에 다음 코드를 복사합니다.

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);
         }
      }
   }
?>

resourceslocaleslocales 디렉토리를 만듭니다. locales 디렉터리 아래에 en_US, fr_FR, de_DE라는 디렉터리 3개를 만듭니다. default.po.라는 각 디렉터리 아래에 파일을 만듭니다. 해당 파일에 다음 코드를 복사합니다.

자원/로케일/en_US/default.po

msgid "msg"
msgstr "CakePHP Internationalization example."

자원/로케일/fr_FR/default.po

msgid "msg"
msgstr "Exemple CakePHP internationalisation."

자원/로케일/de_DE/default.po

msgid "msg"
msgstr "CakePHP Internationalisierung Beispiel."

src/TemplateLocalizations 디렉토리를 생성하고 해당 디렉토리 아래에 index.php라는 View 파일을 생성합니다. 해당 파일에 다음 코드가 있습니다.

src/Template/Localizations/index.php

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

다음 URL에 접속하여 위의 예시를 실행해 보세요. http://localhost/cakephp4/locale

출력

실행하면 다음과 같은 결과가 출력됩니다.

CakePHP 국제화

이메일

CakePHP는 이메일 관련 기능을 관리하기 위한 이메일 클래스를 제공합니다. 모든 컨트롤러에서 이메일 기능을 사용하려면 먼저 다음 줄을 작성하여 이메일 클래스를 로드해야 합니다.

use Cake\Mailer\Email;

Email 클래스는 아래에 설명된 다양하고 유용한 메소드를 제공합니다.

구문
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 )
매개변수
  • 이메일이 포함된 문자열
    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

배열|$this
설명
어디에서 보낸 이메일 주소인지 지정합니다. 이메일이 전송됩니다
Syntax

Subject(string|null $subjectnull)

Parameters
  • Subject string

Returns

array|$this

Description

Get/Set Subject

구문
받는 사람(string|array|null $emailnull, string|null $namenull)
매개변수
  • 이메일이 포함된 문자열
  • 이름
반품 배열|$this
설명 이메일을 누구에게 보낼지 지정합니다
구문
보내기(문자열|배열|null $contentnull)
매개변수
  • 메시지가 포함된 문자열 또는 메시지가 포함된 배열
반품 배열
설명 지정된 콘텐츠, 템플릿 및 레이아웃을 사용하여 이메일 보내기
구문
제목(문자열|null $subjectnull)
매개변수
  • 제목 문자열
반품 배열|$this
설명 제목 가져오기/설정
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();
});

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');
      }
   }
?>

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.

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

위 내용은 CakePHP 국제화의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:CakePHP 양식 처리다음 기사:CakePHP 양식 처리