Symfony2 实现数据库翻译的最佳方法

4
我正在将一个多语言网站重构为Symfony。该网站有许多存储在数据库中的语言内容(产品描述、产品名称等)和一个语言表。它看起来很像这样: 产品表: -id -价格 -库存 -...
产品语言表: -id_product -id_language -名称 -描述
语言表: -id -名称 -代码
因此,我正在考虑将其迁移到Symfony和Doctrine的最佳方式,我一直在研究可翻译扩展,但我不知道它是否适用于此(我不确定是否可以将语言表添加到其中)。
谢谢!
2个回答

4

我使用KNP可翻译行为构建了一个多语言电子商务平台,它非常棒。

它绝对适合您的需求。以下是我的“产品”实体的快速示例以及它如何影响您的数据库。

//AcmeBundle/Entity/Product.php
use Knp\DoctrineBehaviors\Model as ORMBehaviors;

/**
 * @ORM\Table(name="product")
 */
class Product
{
    use ORMBehaviors\Translatable\Translatable;

    /**
     * @var integer
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(name="sku", type="string", length=255)
     */
    protected $sku;

    // other properties

然后将所有可翻译的属性放入一个名为ProductTranslation的新实体中。

//AcmeBundle/Entity/ProductTranslation.php
use Knp\DoctrineBehaviors\Model as ORMBehaviors;

/**
 * @ORM\Table(name="product_translation")
 * @ORM\Entity
 */
class ProductTranslation
{
    use ORMBehaviors\Translatable\Translation,
        ORMBehaviors\Sluggable\Sluggable;

    /**
     * @ORM\Column(name="name", type="string", length=255)
     */
    protected $name;

    /**
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    protected $description; 

这将为您提供两个表格。
第一个表格包含所有产品信息(在此示例中为SKU)。第二个表格将使用1-N关系为每个翻译实例添加一行。
完成后,您可以使用以下任一选项:
$product->translate('en')->getName();
$product->translate('fr')->getName();

或者更好的是

$product->getName();

将使用当前用户的语言环境来输出良好的翻译。


1
请问您能否添加一段Twig中使用翻译的代码示例? - A.L
@A.L 当然,我最近很忙,但我会尝试在周末更新我的答案。祝好。 - Michael Villeneuve

0
你可以使用VM5的实体翻译包。 它非常简单,轻量级,并且还使用本机Doctrine ORM关联进行翻译。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接