PHPackages                             admad/cakephp-i18n - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. admad/cakephp-i18n

ActiveCakephp-plugin[Validation &amp; Sanitization](/categories/validation)

admad/cakephp-i18n
==================

A CakePHP plugin for I18n related tools.

3.1.1(1y ago)4449.5k↓20.3%16[1 issues](https://github.com/ADmad/cakephp-i18n/issues)MITPHPCI passing

Since Dec 18Pushed 5mo ago8 watchersCompare

[ Source](https://github.com/ADmad/cakephp-i18n)[ Packagist](https://packagist.org/packages/admad/cakephp-i18n)[ Docs](https://github.com/ADmad/cakephp-i18n)[ GitHub Sponsors](https://github.com/ADmad)[ RSS](/packages/admad-cakephp-i18n/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (22)Used By (0)

CakePHP plugin for I18n related tools.
======================================

[](#cakephp-plugin-for-i18n-related-tools)

[![Build Status](https://camo.githubusercontent.com/aa8a8f2ec9477d0dfac9467099247d18997cc382e736d4e252314619bcc9ae71/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f41446d61642f63616b657068702d6931386e2f63692e796d6c3f6272616e63683d6d6173746572267374796c653d666c61742d737175617265)](https://github.com/ADmad/cakephp-i18n/actions/workflows/ci.yml?query=branch%3Amaster)[![Coverage Status](https://camo.githubusercontent.com/a7a3c0ebbe0c6ffbc74d52058e43c4746c5cc76d05d8c0fcb57e7db0ce7d28c4/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f41446d61642f63616b657068702d6931386e2e7376673f7374796c653d666c61742d737175617265)](https://codecov.io/github/ADmad/cakephp-i18n)[![Total Downloads](https://camo.githubusercontent.com/49742a757cdd9b8360407dcae9694409589c882c51858f9e7890e83c23412252/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f41446d61642f63616b657068702d6931386e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ADmad/cakephp-i18n)[![License](https://camo.githubusercontent.com/942e017bf0672002dd32a857c95d66f28c5900ab541838c6c664442516309c8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](LICENSE.txt)

Intro
=====

[](#intro)

This plugins provides:

- A route class for generating and matching urls with language prefix.
- A middleware which sets locale using `I18n::setLocale()`based on language prefix in URL and also provides redirection to appropriate URL with language prefix when accessing site root.
- A class for retrieving translation messages stored in the database instead of using po/mo files.
- A validation class for auto translating validation message.
- A widget to generate select box with list of timezone identifiers.

Installation
------------

[](#installation)

```
composer require admad/cakephp-i18n
```

Usage
-----

[](#usage)

Load the plugin by running command:

```
bin/cake plugin load ADmad/I18n
```

The plugin contains multiple classes useful for internationalization. You can pick and chose the ones you require.

### I18nRoute

[](#i18nroute)

The `I18nRoute` class helps generating language prefixed routes of style `/{lang}/{controller}/{action}`.

For e.g. you can add routes to your `routes.php` similar to the ones shown below:

```
$routes->scope('/', function ($routes) {
    $routes->connect(
        '/{controller}',
        ['action' => 'index'],
        ['routeClass' => 'ADmad/I18n.I18nRoute']
    );
    $routes->connect(
        '/{controller}/{action}/*',
        [],
        ['routeClass' => 'ADmad/I18n.I18nRoute']
    );
});
```

Fragment `/{lang}` will be auto prefixed to the routes which allows matching URLs like `/en/posts`, `/en/posts/add` etc. The `lang` element is persisted so that when generating URLs if you don't provide the `lang` key in URL array it will be automatically added based on current URL.

When connecting the routes you can use `lang` key in options to provide regular expression to match only languages which your app supports. Or your can set config value `I18n.languages`, which the route class will use to auto generate regex for `lang` element matching:

```
// In your config/app.php
    ...
    'I18n' => [
        'languages' => ['en', 'fr', 'de']
    ]
    ...
```

Note: `I18nRoute` extends core's `DashedRoute` so the URL fragments will be inflected accordingly.

### I18nMiddleware

[](#i18nmiddleware)

While not necessary, one would generally use the `I18nMiddleware` too when using language prefixed routes with the help of `I18nRoute`.

You can setup the `I18nMiddleware` in your `src/Application::middleware()` as shown:

```
$middlware->add(new \ADmad\I18n\Middleware\I18nMiddleware([
    // If `true` will attempt to get matching languges in "languages" list based
    // on browser locale and redirect to that when going to site root.
    'detectLanguage' => true,
    // Default language for app. If language detection is disabled or no
    // matching language is found redirect to this language
    'defaultLanguage' => 'en',
    // Languages available in app. The keys should match the language prefix used
    // in URLs. Based on the language the locale will be also set.
    'languages' => [
        'en' => ['locale' => 'en_US'],
        'fr' => ['locale' => 'fr_FR'],
    ],
]));
```

The keys of `languages` array are the language prefixes you use in your URL.

To ensure that the `lang` router param is available, you must add this middleware *after* adding CakePHP's default routing middleware (i.e. after `->add(new RoutingMiddleware($this))`).

The middleware does basically two things:

1. When accessing site root `/` it redirects the user to a language prefixed URL, for e.g. `/en`. The langauge it redirects to depends on the configuration keys `detectLanguage` and `defaultLanguage` shown above.

    Now in order to prevent CakePHP from complaining about missing route for `/`, you must connect a route for `/` to a controller action. That controller action will never be actually called as the middleware will intercept and redirect the request.

    For e.g. `$routes->connect('/', ['controller' => 'Foo']);`
2. When accesing any URL with language prefix it sets the app's locale based on the prefix. For that it checks the value of `lang` route element in current request's params. This route element would be available if the matched route has been connected using the `I18nRoute`.

    Using the array provided for the `languages` key it sets the `App.language`config to the language prefix through `Configure::write()` and the value of `locale`is used for the `I18n::setLocale()` call.

### DbMessagesLoader

[](#dbmessagesloader)

By default CakePHP uses `.po` files to store the static string translations. If for whatever reason you can't/don't want to use `.po` files, you can use the `DbMessagesLoader` to store the translation messages in the database instead. Personally I belive having the messages in a table instead of `.po` files makes it much easier to make a web interface for managing translations.

To use this class first create the `i18n_messages` database table using the sql file provided in the plugin's `config` folder.

Add code similar to what's shown below in your app's `config/bootstrap.php`:

```
// NOTE: This is should be done below Cache config setup.

// Configure `I18n` to use `DbMessagesLoader` for the `default` domain. You need to do
// this for each domain separately.
\Cake\I18n\I18n::config('default', function ($domain, $locale) {
    $loader = new \ADmad\I18n\I18n\DbMessagesLoader(
        $domain,
        $locale
    );

    return $loader();
});
```

Now you can use the translation functions like `__()` etc. as you normally would. The `I18n` class will fetch the required translations from the `i18n_messages`table instead of `.po` files.

Use the `admad/i18n extract` command to extract the translation messages from your code files and populate the translations table. Updating the database records with translations for each language is upto you.

```
bin/cake admad/i18n extract
```

The extract command needs the list of languages/locales to populate the `i18n_messages`table. This can be done by setting the `I18n.languages` config **or** by specifying the languages list using the `languages` option.

```
// In your config/app.php
    ...
    'I18n' => [
        'languages' => ['en', 'fr', 'de']
    ]
    ...
```

```
bin/cake admad/i18n extract --languages en,fr,de
```

You can run the command multiple times as needed. It will add new messages it finds to the tables, keeping the ones already present untouched.

### TimezoneWidget

[](#timezonewidget)

In your `AppView::initialize()` configure the `FormHelper` to use `TimezoneWidget`.

```
// src/View/AppView.php
public function initialize(): void
{
    $this->loadHelper('Form', [
        'widgets' => [
            'timezone' => ['ADmad/I18n.Timezone'],
        ],
    ]);
}
```

You can generate a select box with timezone identifiers like:

```
// Generates select box with list of all timezone identifiers grouped by regions.
$this->Form->control('fieldname', ['type' => 'timezone']);

// Generates select box with list of timezone identifiers for specified regions.
$this->Form->control('fieldname', [
    'type' => 'timezone',
    'options' => [
        'Asia' => DateTimeZone::ASIA,
        'Europe' => DateTimeZone::EUROPE,
    ],
]);
```

As shown in example above note that unlike normal select box, `options` is now an associative array of valid timezone regions where the key will be used as `optgroup` in the select box.

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance56

Moderate activity, may be stable

Popularity44

Moderate usage in the ecosystem

Community20

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 98.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~153 days

Recently: every ~10 days

Total

20

Last Release

527d ago

Major Versions

1.2.1 → 2.0.0-beta2019-12-17

1.x-dev → 2.0.0-RC22020-06-14

2.2.1 → 3.0.02023-09-29

2.2.2 → 3.1.12024-12-07

### Community

Maintainers

![](https://www.gravatar.com/avatar/e31753bdd616948c7c8978ea9b5805378f75bfa62564e69c0aa2fd67aaf418c5?d=identicon)[ADmad](/maintainers/ADmad)

---

Top Contributors

[![ADmad](https://avatars.githubusercontent.com/u/142658?v=4)](https://github.com/ADmad "ADmad (242 commits)")[![dereuromark](https://avatars.githubusercontent.com/u/39854?v=4)](https://github.com/dereuromark "dereuromark (1 commits)")[![JD-Robbs](https://avatars.githubusercontent.com/u/5319760?v=4)](https://github.com/JD-Robbs "JD-Robbs (1 commits)")[![joshwyrick](https://avatars.githubusercontent.com/u/12661899?v=4)](https://github.com/joshwyrick "joshwyrick (1 commits)")[![romainbu](https://avatars.githubusercontent.com/u/12477600?v=4)](https://github.com/romainbu "romainbu (1 commits)")

---

Tags

cakephpcakephp-plugini18nphptranslationvalidationi18ncakephproutingmessages

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/admad-cakephp-i18n/health.svg)

```
[![Health](https://phpackages.com/badges/admad-cakephp-i18n/health.svg)](https://phpackages.com/packages/admad-cakephp-i18n)
```

###  Alternatives

[apy/jsfv-bundle

Symfony2 Javascript Form Validation Bundle with localisation support

92770.5k](/packages/apy-jsfv-bundle)[laravel-lang/attributes

Translation of form element names

273.8M11](/packages/laravel-lang-attributes)[ichikaway/cakeplus

Cake plus is cakephp plugin and provides some functions for CakePHP.

52101.1k1](/packages/ichikaway-cakeplus)[chrisshick/cakephp3-html-purifier

This is a CakePHP3 Purifier Plugin Behavior that cleanses data before it is marshalled into the entity.

12168.1k](/packages/chrisshick-cakephp3-html-purifier)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
