anahkiasen / 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: 2020-02-07 14:49:37 UTC
README
简介
Polyglot 是 Laravel 框架的本地化辅助工具,它是一个帮助类,用于本地化你的路由、模型和视图。
要安装它,请执行 composer require anahkiasen/polyglot:dev-master
,然后添加 Polyglot\PolyglotServiceProvider
到 app/config/app.php
中的 providers
数组。
将配置发布到您的 Laravel 应用: php artisan config:publish anahkiasen/polyglot
模型本地化
将模型设置为 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 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 的 gettext 的 twig/extensions
包。
要使用它,只需在配置中配置您的域,然后运行 php artisan lang:extract
。
区域设置辅助函数
Polyglot 还提供了各种区域设置辅助函数,这些函数已经连接到您熟悉的 Lang
和 URL
类。
URL::locale() // Returns the locale in the current URL 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