nkt/translate-bundle

此包为 Doctrine 实体提供翻译机制

安装: 16

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

开放问题: 0

类型:symfony-bundle

dev-master / 0.1.x-dev 2014-09-04 22:36 UTC

This package is auto-updated.

Last update: 2024-09-04 12:23:53 UTC


README

此包为 Doctrine 实体提供翻译机制。

安装

将以下内容添加到您的 composer.json

{
    "require": {
        "nkt/translate-bundle": "~0.1"
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

在内核中启用此包

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Nkt\TranslateBundle\NktTranslateBundle(),
    );
}

使用方法

让我们为简单的博客创建实体。

<?php

namespace Acme\BlogBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Nkt\TranslateBundle\Behavior as TranslateBehavior;

class Post implements TranslateBehavior\LocaleAware
{
    use TranslateBehavior\Translatable;
    
    /**
     * @var int
     */
    private $id;
    
    public function __construct()
    {
        $this->translations = new ArrayCollection();
    }
    
    public function getId()
    {
        return $this->id;
    }
}

现在我们需要创建一个翻译实体。

<?php

namespace Acme\BlogBundle\Entity;

use Nkt\TranslateBundle\Behavior as TranslateBehavior;

class PostTranslation
{
    use TranslateBehavior\Translation;
    
    private $title;
    private $content;

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    public function getContent()
    {
        return $this->content;
    }

    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }
}

现在您可以使用它。

public function newPostAction(Request $request)
{
    $post = new Post();
    foreach ($request->request->get('translations') as $translation) {
        $post->translate($translation['locale'])
             ->setTitle($translation['title'])
             ->setContent($translation['content']);
    }
    ...
}

translate 方法会寻找给定 $locale 的翻译,如果没有找到,则会创建它。

getTranslation 方法会寻找给定 $locale 的翻译,如果没有找到,则会寻找 currentLocale 翻译。

LocaleAware 接口

如果您想在可翻译实体中注入应用程序区域设置,您应该实现 Nkt\TranslateBundle\Behavior\LocaleAware 接口。默认情况下,每个可翻译实体的 currentLocale 等于 en

许可证

MIT