admad/cakephp-i18n
Composer 安装命令:
composer require admad/cakephp-i18n
包简介
A CakePHP plugin for I18n related tools.
README 文档
README
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
composer require admad/cakephp-i18n
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
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
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:
-
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 keysdetectLanguageanddefaultLanguageshown 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']); -
When accesing any URL with language prefix it sets the app's locale based on the prefix. For that it checks the value of
langroute element in current request's params. This route element would be available if the matched route has been connected using theI18nRoute.Using the array provided for the
languageskey it sets theApp.languageconfig to the language prefix throughConfigure::write()and the value oflocaleis used for theI18n::setLocale()call.
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
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.
admad/cakephp-i18n 适用场景与选型建议
admad/cakephp-i18n 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 55.65k 次下载、GitHub Stars 达 44, 最近一次更新时间为 2015 年 07 月 19 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「routing」 「i18n」 「validation」 「cakephp」 「messages」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 admad/cakephp-i18n 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 admad/cakephp-i18n 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 admad/cakephp-i18n 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Easy to use i18n translation PHP class for multi-language websites
A custom URL rule class for Yii 2 which allows to create translated URL rules
Write down your routing mapping at one place
Bureaux A Partager Edit - Parse, validate, manipulate, and display dates in PHP w/ i18n support. Inspired by moment.js
Nette Framework adapter for I18n package
Flight routing is a simple, fast PHP router that is easy to get integrated with other routers.
统计信息
- 总下载量: 55.65k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 45
- 点击次数: 27
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-07-19