記錄一下怎麼在 CodeIgniter 4 製作多語系架構:

Locale Configuration Settings

設定 config:打開 /app/Config/App.php 的檔案,找到以下這段:

public $negotiateLocale = false;

改成

public $negotiateLocale = true;

 

找到這段

public array $supportedLocales = ['en'];

改成你要支援的語系,比如:

public array $supportedLocales = ['en', 'zh-TW', 'zh-CN'];

 

Language Controller Settings

打開 /app/Controllers/BaseController.php,把 helpers 加上 url:

protected $helpers = ["url"];

 

接著建立一個新的 Controller 並命名為 Language.php,內容如下

namespace App\Controllers;

use App\Controllers\BaseController;

class Language extends BaseController
{
    public function index()
    {
        $session = session();
        $locale = $this->request->getLocale();
        $session->remove('lang');
        $session->set('lang', $locale);
        $url = base_url();
        return redirect()->to($url);
    }
}

程式碼說明:

 

  • $session = session(); // Creating session service instance variable.
  • $locale = $this->request->getLocale(); // Reading requested locale and storing into $locale variable.
  • $session->remove(‘lang’); // Removing existing saved locale “lang” key from session
  • $session->set(‘lang’, $locale); // Saving requested locale into “lang” session key
  • $url = base_url(); // Getting application base URL
  • redirect()->to($url) // Redirecting to base URL

這個是把語系的變數存在 session,我實際上在做有再把 session 的資料與網址做連動。

 

Parent Controller Settings

修改 BaseController.php:

public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
    // Do Not Edit This Line
    parent::initController($request, $response, $logger);

    // Add these lines
    $session = \Config\Services::session();
    $language = \Config\Services::language();
    $language->setLocale($session->lang);
}
//...

 

多語系檔設定

CodeIgniter 4 的多語系檔在 /app/Language 的資料夾內,你可以依據需求建立對應的語系資料夾,比如:

  • /app/Language/en
  • /app/Language/zh-TW
  • /app/Language/zh-CN

 

Setup Language Keys & Texts

接著在裡面每個資料夾內都建立一個同樣檔名的 php 檔,病癒 key => value 的方式設定內如,比如建立一支 Text.php 的檔案,裡面可以像這樣設定:

return [
    'page_title' => 'Home',
    'welcome_message' => 'Hi, Welcome to this page',
    'intro' => 'My name is Deathhell.',
];

可以根據不同資料夾在每個 key 輸入不同內容即可。

 

View File

建立一個 site 的 Controller,並在裡面這樣設定:

namespace App\Controllers;

use App\Controllers\BaseController;

class Site extends BaseController
{
    public function index()
    {
        return view("home");
    }
}

 

接著在 view 裡像這樣就能讀取跟切換語系了:

<a href="<?= site_url('lang/en'); ?>">English</a>
<a href="<?= site_url('lang/zh-TW'); ?>">繁體中文</a>
<a href="<?= site_url('lang/zh-CN'); ?>">簡体中文</a>

<h1><?= lang("Text.page_title") ?></h1>
<h2><?= lang("Text.welcome_message") ?></h2>
<h3><?= lang("Text.info") ?></h3>

讀取的規則就是語系檔名.key 這樣。

 

設定 Route

設定 Route 後,就可以運作了:

$routes->get('/', 'Site::index');
$routes->get('lang/{locale}', 'Language::index');

不過這個只是基本的設定,像設定完 session 後會導回首頁,如果要每頁都能切換就也要在自己調整一下程式碼。

參考:
How To Create Multilingual Website in CodeIgniter 4