gentor / polyglot
Laravel 国际化辅助工具和模型
Requires
- php: >=5.4.0
- illuminate/container: ~4.2
- illuminate/support: ~4.2
Requires (Dev)
- fabpot/php-cs-fixer: 2.0.*@dev
- illuminate/database: ~4.2
- illuminate/routing: ~4.2
- illuminate/translation: ~4.2
- mockery/mockery: ^0.9.4
- patchwork/utf8: ^1.2
- phpunit/phpunit: ^4.7
This package is auto-updated.
Last update: 2024-09-09 03:21:33 UTC
README
简介
Polyglot 是 Laravel 框架的国际化辅助工具,它是一个辅助类,用于本地化您的路由、模型和视图。
要安装它,请执行 composer require anahkiasen/polyglot
,然后向 app/config/app.php
中的 providers
数组添加 Polyglot\PolyglotServiceProvider
。
将配置发布到您的 Laravel 应用:php artisan vendor:publish --provider=Polyglot\PolyglotServiceProvider
模型本地化
在模型上使用 Polyglot 特性将允许您使字段支持多种语言。Polyglot 假定以下常见模式,要求您将常用字段与本地化字段分开:
以博客文章模型为例
TABLE articles
id INT
category_id INT
created_at DATETIME
updated_at DATETIME
TABLE article_langs
id INT
title VARCHAR
content TEXT
article_id INT
lang ENUM
您可以通过以下方式轻松访问任何语言:$article->fr->title
。或者,您可以在模型中添加以下参数,让 Polyglot 自动翻译属性。
class Article extends Model { use Polyglot\Polyglot; protected $polyglot = ['title', 'content']; } // Get an automatically localized Article $article = Article::find(4) echo $article->fr->title // This will print out the french title echo $article->title // This will print out the title in the current language
Polyglot 还帮助您保存本地化属性
$article->fill([ 'title' => 'Titre', 'content' => 'Contenu', 'lang' => 'fr', ])->save(); // Is the same as $article->fr->fill([ 'title' => 'Titre', 'content' => 'Contenu', ])->save();
一般来说,当 Polyglot 发现您正在尝试在父模型上保存本地化属性时,它将自动获取 Lang 模型并将它们保存在上面。如果没有传递 lang
属性,Polyglot 将使用当前语言。
请注意,由于您的属性现在被分成两个表,您可以使用 Polyglot 的 withLang
方法预加载正确的 Lang 关系。例如,Article::withLang()->get()
将返回具有已自动加载的 fr
的文章,如果它是当前语言,或者 en
,根据 app.locale
。
路由本地化
要本地化您的路由,您需要设置配置文件中的 locales
选项,例如 array('fr', 'en')
。现在您可以这样定义您的路由
Route::groupLocale(['before' => 'auth'], function() { Route::get('/', 'HomeController@index'); Route::get('articles', 'ArticlesController@index'); // etc... });
现在您可以访问 /fr
和 /fr/articles
,或 /en
和 /en/articles
。Polyglot 将识别 URL 中的区域设置并将其自动设置为该语言。配置文件中还有一个 default
选项,将该选项设置为区域设置,例如 'default' => 'fr'
将使根 URL 指向该区域设置。因此,访问不带区域设置前缀的 /articles
将显示法语页面。
视图本地化
视图本地化通过为您设置 gettext 并提供两个命令从您的视图提取翻译到 PO 文件并编译这些文件到 MO 文件来实现。
目前这仅适用于 Twig,但很快将适用于 Blade 和经典 PHP 文件,并且需要 twig/extensions
包,它为 Twig 添加了 gettext 支持。
要使用,只需在配置中配置您的域,然后运行 php artisan lang:extract
。
区域设置助手
Polyglot 还提供各种区域设置助手,这些助手连接到您所熟知的 Lang
和 URL
类。
URL::locale() // Returns the locale in the current URL URL::switchLanguage('fr') // Returns the current url with different locale Lang::active('fr') // Check if fr is the current locale Lang::setInternalLocale('fr') // Set both the locale with the Translator class and setlocale method Lang::valid('fr') // Check if a locale is valid Lang::sanitize('fr') // Returns the locale if valid, or the default locale if not