upon/mlang

适用于大型数据库的多语言包,响应速度快

v1.0.12 2024-05-23 10:58 UTC

README

Build Status License

此包是一个高性能解决方案,旨在为Laravel应用程序提供高效的多种语言支持。它提供强大的功能和优化,确保快速且可靠的语言管理,使您的应用程序能够服务于全球受众,同时不牺牲性能。

特性

  • 加速翻译检索:从相同的数据库表高效检索翻译字符串,最小化数据库连接查询并提高响应时间。

  • 与Laravel无缝集成:该包与Laravel无缝集成,利用其现有的本地化基础设施,同时提供性能增强。

  • 翻译助手:您可以使用辅助函数和方法将应用程序的内容翻译成不同的语言。这些助手使检索和显示翻译字符串变得容易。

  • 语言检测:该包包括基于用户浏览器设置的自动语言检测。它还支持用户手动选择语言。

  • 语言回退:如果某个语言的翻译缺失,该包支持回退到默认或替代语言。这确保了用户始终看到支持的语言内容。

注意

此包将为您使用的模型添加两个额外列,row_id和iso。包将使用row_id作为id,从数据库中检索正确的行。

  • row_id:此列将持有所有语言的 主主键。
  • iso:此列持有语言键,例如en,nl,fr等...

要求

  • PHP >= 8.1
  • Laravel >= 10.0

*** 此包需要以下包。 ***

composer require doctrine/dbal

安装

1 - 使用Composer安装包

composer require upon/mlang

2 - 发布包配置和语言文件

php artisan vendor:publish --tag="mlang"

3 - 根据您的需求修改config/mlang.php文件以配置包。

您可以选择支持的区域设置、默认区域设置、模型和其他选项。

4 - 在mlang配置文件中配置所需的翻译模型。

// ...
'models' => [
    \App\Models\Category::class,
    \App\Models\Product::class,
    // ...
]
// ...

5- 用MlangModel替换默认扩展模型。

<?php
// ...
use Upon\Mlang\Models\MlangModel;

class Category extends MlangModel
{
    // ...

6 - 运行迁移命令,将新列迁移到添加的模型中。

    php artisan mlang:migrate

###管理现有记录的翻译

  • 要为现有行生成翻译,请使用以下命令
php artisan mlang:generate
  • 要在特定表中生成,请使用以下命令
/** Replace {model} with the desired model you need 
 * (e.g., category or in subdirectory dir\\Category).
 * This using the default model path [App\\Models]
 * you can update the model path in the config file.  
 */
php artisan mlang:generate {model}
  • 要生成特定语言代码,请使用以下命令
/** 
 * all to run all models or specify one model name (e.g., Sub\\Category).
 * Replace {locale} with the desired language code (e.g., en for English).
 */
php artisan mlang:generate {model|all} {locale}
  • 要从表中删除语言,请使用以下命令
/**
 * Replace {locale} with the desired language code (e.g., en for English).
 * Replace {table} with the desired table name (e.g., categories).  
 */
php artisan mlang:remove {table} {locale}
  • 该包包括基于用户浏览器语言的自动语言检测。它使用Accept-Language头或浏览器设置来确定首选语言。
    • (可选) 将区域中间件添加到app/Http/Kernel.php文件中的$middlewareGroups属性:用于检测用户浏览器语言。
 protected $middlewareGroups = [
'web' => [
// ...
\Upon\Mlang\Middleware\DetectUserLanguageMiddleware::class,
],

    // ...
];

要手动设置用户的语言,您可以使用setLocale()方法

/** Replace {locale} with the desired language code. */
app()->setLocale('{locale}');

用法

要按id从数据库中查找记录,您可以这样做。
这将根据应用程序当前使用的语言获取翻译记录。

    Model::trFind(1);

trWhere方法将像正常的where一样工作,但会将id映射到row_id列,以便选择当前语言。这将返回一个构建对象,因此您可以将其与其他查询链式使用。

    /** This will get a collection based on the current language*/
    Model::trWhere(['name' => 'test'])->get();

### 贡献

欢迎贡献!如果您遇到任何问题、有建议或希望为该包做出贡献,请在该包的GitHub仓库中创建一个问题或提交一个pull request。

### 许可证

此包是开源软件,许可协议为MIT许可。请随意使用、修改和根据许可证条款分发。

致谢

此包由Reymon Zakhary开发。特别感谢Laravel社区的支持和灵感。

联系方式

如果您有任何问题或需要进一步的帮助,可以通过reymon@charisma-design.eu联系包的维护者。