jc-it/yii2-i18n-model

用于处理模型翻译的辅助工具。

v1.0.2 2023-03-07 12:20 UTC

This package is auto-updated.

Last update: 2024-09-07 15:18:03 UTC


README

codecov Continous integration Packagist Total Downloads Packagist Monthly Downloads GitHub tag (latest by date) Packagist Version

此扩展提供了一个包,实现了与模型属性翻译一起工作的特性和行为。

$ composer require jc-it/yii2-i18n-model

或添加

"jc-it/yii2-i18n-model": "^<latest version>"

到您的 composer.json 文件的 require 部分。

配置

Active Record 模型

将行为添加到您的 AR 模型,并确保它有一个 i18n 属性

public function behaviors(): array
{
    return [
        \JCIT\i18n\behaviors\I18nBehavior::class => [
            'class' => \JCIT\i18n\behaviors\I18nBehavior::class,
            'attributes' => [
                '<attribute>',
            ],       
        ]       
    ]; 
}

在规则中,只需像平时那样定义规则即可

public function rules(): array
{
    return [
        [['<attribute>'], \yii\validators\RequiredValidator::class],
        [['<attribute>'], \yii\validators\StringValidator::class],
    ]; 
}

为了设置属性或保存它,首先设置地区,然后保存

$model = new ClassWithI18nBehavior();
$model->locale = 'en-US';
$model-><attribute> = 'value en';
$model->save();

$model->locale = 'nl-NL';
$model-><attribute> = 'value nl';
$model->save();

自动将值获取到模型设置的地区

$model = ClassWithI18nBehavior::findOne();
$model->locale = 'en-US';
echo $model-><attribute>; // 'value en'

$model->locale = 'nl-NL';
echo $model-><attribute>; // 'value nl'

表单模型

将特质添加到表单模型

class FormModel extends \yii\base\Model
{
    use \JCIT\i18n\traits\models\I18nTrait;
}

在渲染表单属性时,属性名应该是:i18n[<locale>][<attribute>]

待办事项

  • 修复 PHPStan,重新添加到 captainhook.json
    • {
          "action": "vendor/bin/phpstan",
          "options": [],
          "conditions": []
      },
      
  • 添加测试

鸣谢

许可证

MIT 许可证 (MIT)。更多信息请参阅 LICENSE