bedita/i18n

Bedita 4 & CakePHP 的国际化插件

维护者

详细信息

github.com/bedita/i18n

源代码

问题

安装数量: 85,461

依赖项: 9

建议者: 0

安全: 0

星级: 3

关注者: 7

分支: 1

开放问题: 1

类型:cakephp-plugin

v4.4.3 2023-11-03 07:20 UTC

README

Github Actions codecov phpstan Scrutinizer Code Quality image image

安装

您可以使用以下方式使用composer安装此Bedita4/CakePHP插件:

composer require bedita/i18n

设置

为了使用此插件,您需要在您的应用中加载它,例如在 Application::bootstrap() 中:

$this->addPlugin('BEdita/I18n');

中间件和辅助工具

首先,您需要在应用的 config/bootstrap.php(或者如果您愿意,在 config/app_local.php) 中设置一个 I18n 配置。

/*
 * I18n configuration.
 */
Configure::write('I18n', [
    // list of locales supported
    // locale => primary language code for that locale
    'locales' => [
        'en_US' => 'en',
        'it_IT' => 'it',
    ],
    // default primary language code
    'default' => 'en',
    // list of languages supported
    // primary language code => humanized language
    'languages' => [
        'en' => 'English',
        'it' => 'Italiano',
    ],

    /** Middleware specific conf **/
    // array of URL paths, if there's an exact match rule is applied
    'match' => ['/'],
    // array of URL paths, if current URL path starts with one of these rule is applied
    'startWith' => ['/help', '/about'],
    //reserved URL (for example `/lang`) used to switch language and redirect to referer URL.
    'switchLangUrl' => '/lang',
    // array for cookie that keeps the locale value. By default no cookie is used.
    'cookie' => [
         'name' =>  'i18n-lang', //cookie name
         'create' => true, // set to `true` if the middleware is responsible of cookie creation
         'expire' => '+1 year', // used when `create` is `true` to define when the cookie must expire
    ],
    // session key where store the locale. Set null to disable (default)
    'sessionKey' => 'i18n-session-locale',
]);

I18nMiddleware

BEdita/I18n 插件添加到应用的 Application::bootstrap() 方法中,I18nMiddleware 将在中间件队列中添加到 RoutingMiddleware 之前。

I18n 配置将用于设置中间件配置。

namespace App;

use Cake\Http\BaseApplication;

/**
 * Application setup class.
 */
class Application extends BaseApplication
{
    /**
     * {inheritDoc}
     */
    public function bootstrap(): void
    {
        parent::bootstrap();

        $this->addPlugin('BEdita/I18n');
    }

    // other stuff here
}

您可以选择不添加 I18nMiddleware,因为您的应用不需要它,或者可以在您的应用中程序化地添加它。

namespace App;

use BEdita\I18n\Middleware\I18nMiddleware;
use Cake\Http\BaseApplication;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\MiddlewareQueue;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;

/**
 * Application setup class.
 */
class Application extends BaseApplication
{
    /**
     * {inheritDoc}
     */
    public function bootstrap(): void
    {
        parent::bootstrap();

        // Do not add I18nMiddleware automatically
        $this->addPlugin('BEdita/I18n', ['middleware' => false]);
    }

    /**
     * {@inheritDoc}
     */
    public function middleware($middlewareQueue) : MiddlewareQueue
    {
        $middlewareQueue
            ->add(ErrorHandlerMiddleware::class)
            ->add(AssetMiddleware::class)

            // Add programmatically I18n middleware.
            ->add(new I18nMiddleware())

            ->add(new RoutingMiddleware($this));

        return $middlewareQueue;
    }
}

这样,中间件仅负责使用URI路径和配置设置正确的区域设置。例如,导航到 http://example.com/it/page/one 时,中间件将使用上述配置示例将区域设置设置为 it_IT

您还可以配置中间件将一些URL重定向到它们的i18n版本。

$middlewareQueue->add(new I18nMiddleware([
    'match' => ['/'],
    'startWith' => ['/help/', '/about/'],
]));

所有与 'match' 键中的内容完全匹配或以 'startWith' 中的条目开头的URI路径都将重定向到相同的URL,但带有检测到的语言作为前缀,例如 /it/help

您还可以配置中间件使用cookie来存储区域设置。

$middlewareQueue->add(new I18nMiddleware([
    'cookie' =>[
        'name' => 'I18nLocale',
        'create' => true, // the middleware will create the cookie (default false)
        'expire' => '+1 month', // cookie expiring time (default +1 year)
    ],
]));

I18nRoute

I18nRoute 类可用于简化您编写和匹配路由规则的方式。例如

$routes->connect(
    '/pages',
    [
        'controller' => 'Pages',
        'action' => 'index',
    ],
    [
        '_name' => 'pages:index',
        'routeClass' => 'BEdita/I18n.I18nRoute',
    ]
);

映射到 /:lang/pages,而 I18n.languages 配置中定义的语言代码将用作 :lang 参数的路由模式。

因此,上述规则等同于

$routes->connect(
    '/:lang/pages',
    [
        'controller' => 'Pages',
        'action' => 'index',
    ],
    ['_name' => 'pages:index']
)
->setPatterns(['lang' => 'it|en']);

如果当前语言是 it,则可以获取本地化URL为

// default
$url = \Cake\Routing\Router::url(['_name' => 'pages:index']);
echo $url; // prints /it/pages

// get url with another supported lang
$url = \Cake\Routing\Router::url([
    '_name' => 'pages:index',
    'lang' => 'en',
]);
echo $url; // prints /en/pages

I18nHelper

为了使用此辅助工具,您需要在 AppView::initialize() 方法中初始化它。

public function initialize() : void
{
    parent::initialize();

    $this->loadHelper('BEdita/I18n.I18n');
}

Gettext命令

gettext 命令提供了一种更新Bedita应用和插件中的I18N区域文件的方法。

系统上必须有可用的 msgmerge 二进制文件。在大多数Linux系统中,这通过 gettext 软件包提供。

只需键入

bin/cake gettext

您的代码位于 /src/config,然后解析并提取gettext字符串,寻找 __('Some string') 表达式。然后

  • resources/locales/default.pot gettext主文件被创建或更新,同样,对于可选的域文件,如 mydomain.pot
  • 所有区域文件,如 resources/locales/{locale}/default.po 和其他可选的域文件,如 mydomain.po 也被创建或更新 - 其中 {locale} 是常用的区域表达式,如 en-USde-DEfr-FR

命令选项

--help, -h      Display this help.
--quiet, -q     Enable quiet output.
--verbose, -v   Enable verbose output.
--app, -a       The app path, for i18n update.
--plugin, -p    The plugin path, for i18n update.
--plugins       Apply on all plugins.

您可以通过 --app--plugin 选项在不同的应用或插件路径上调用此命令。