shirase55/yii2-translateable

Yii框架的翻译行为

安装: 10

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 23

类型:yii2-extension

1.0.1 2018-02-26 15:16 UTC

This package is auto-updated.

Last update: 2024-09-05 19:04:34 UTC


README

Build Status Code Coverage Code Quality Packagist Version

为Yii框架提供的现代翻译行为。

安装

首选安装此扩展的方式是通过 composer

运行以下命令

$ composer require creocoder/yii2-translateable

或在您的 composer.json 文件的 require 部分添加以下内容

"creocoder/yii2-translateable": "~1.0"

迁移

运行以下命令

$ yii migrate/create create_post_table

打开 /path/to/migrations/m_xxxxxx_xxxxxx_create_post_table.php 文件,在 up() 方法中添加以下内容

$this->createTable('{{%post}}', [
    'id' => Schema::TYPE_PK,
]);

运行以下命令

$ yii migrate/create create_post_translation_table

打开 /path/to/migrations/m_xxxxxx_xxxxxx_create_post_translation_table.php 文件,在 up() 方法中添加以下内容

$this->createTable('{{%post_translation}}', [
    'post_id' => Schema::TYPE_INTEGER . ' NOT NULL',
    'language' => Schema::TYPE_STRING . '(16) NOT NULL',
    'title' => Schema::TYPE_STRING . ' NOT NULL',
    'body' => Schema::TYPE_TEXT . ' NOT NULL',
]);

$this->addPrimaryKey('', '{{%post_translation}}', ['post_id', 'language']);

配置

按照以下方式配置模型

use creocoder\translateable\TranslateableBehavior;

/**
 * ...
 * @property string $title
 * @property string $body
 * ...
 */
class Post extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            'translateable' => [
                'class' => TranslateableBehavior::className(),
                'translationAttributes' => ['title', 'body'],
                // translationRelation => 'translations',
                // translationLanguageAttribute => 'language',
            ],
        ];
    }

    public function transactions()
    {
        return [
            self::SCENARIO_DEFAULT => self::OP_INSERT | self::OP_UPDATE,
        ];
    }

    public function getTranslations()
    {
        return $this->hasMany(PostTranslation::className(), ['post_id' => 'id']);
    }
}

可以使用Gii生成 PostTranslation 模型。

用法

设置实体的翻译

要将翻译设置到实体中

$post = new Post();

// title attribute translation for default application language
$post->title = 'Post title';

// body attribute translation for default application language
$post->body = 'Post body';

// title attribute translation for German
$post->translate('de-DE')->title = 'Post titel';

// body attribute translation for German
$post->translate('de-DE')->body = 'Post inhalt';

// title attribute translation for Russian
$post->translate('ru-RU')->title = 'Заголовок поста';

// body attribute translation for Russian
$post->translate('ru-RU')->body = 'Тело поста';

// save post and its translations
$post->save();

从实体中获取翻译

从实体中获取翻译

$posts = Post::find()->with('translations')->all();

foreach ($posts as $post) {
    // title attribute translation for default application language
    $title = $post->title;

    // body attribute translation for default application language
    $body = $post->body;

    // title attribute translation for German
    $germanTitle = $post->translate('de-DE')->title;

    // body attribute translation for German
    $germanBody = $post->translate('de-DE')->body;

    // title attribute translation for Russian
    $russianTitle = $post->translate('ru-RU')->title;

    // body attribute translation for Russian
    $russianBody = $post->translate('ru-RU')->body;
}

检查实体中的翻译

检查实体中的翻译

$post = Post::findOne(1);

// checking for default application language translation
$result = $post->hasTranslation();

// checking for German translation
$result = $post->hasTranslation('de-DE');

// checking for Russian translation
$result = $post->hasTranslation('ru-RU');

高级用法

收集表格输入

控制器操作的示例

class PostController extends Controller
{
    public function actionCreate()
    {
        $model = new Post();

        foreach (Yii::$app->request->post('PostTranslation', []) as $language => $data) {
            foreach ($data as $attribute => $translation) {
                $model->translate($language)->$attribute = $translation;
            }
        }

        //...
    }

    public function actionUpdate($id)
    {
        $model = Post::find()->with('translations')->where(['id' => $id])->one();

        if ($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        foreach (Yii::$app->request->post('PostTranslation', []) as $language => $data) {
            foreach ($data as $attribute => $translation) {
                $model->translate($language)->$attribute = $translation;
            }
        }

        //...
    }
}

视图表单的示例

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin();

foreach (['en-US', 'de-DE', 'ru-RU'] as $language) {
    echo $form->field($model->translate($language), "[$language]title")->textInput();
    echo $form->field($model->translate($language), "[$language]body")->textarea();
}

//...

ActiveForm::end();

特定语言的翻译属性标签

模型属性标签的示例

class PostTranslation extends \yii\db\ActiveRecord
{
    public function attributeLabels()
    {
        switch ($this->language) {
            case 'de-DE':
                return [
                    'title' => 'Titel',
                    'body' => 'Inhalt',
                ];
            case 'ru-RU':
                return [
                    'title' => 'Заголовок',
                    'body' => 'Тело',
                ];
            default:
                return [
                    'title' => 'Title',
                    'body' => 'Body',
                ];
        }
    }
}

捐赠

通过gratipay支持此项目和 creocoder 的其他项目。

Support via Gratipay