定制 arxy/entity-translations-bundle 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

arxy/entity-translations-bundle

Composer 安装命令:

composer require arxy/entity-translations-bundle

包简介

This bundle provides translations for entities in your project. It's a bundle, but can be used standalone.

关键字:

README 文档

README

Build Status

codecov

Very simple bundle that allows you to translate your entities.

Installation:

it is recommented to install X.Y.* version - This project follow semver - Patch versions will be always compatible with each other. Minor versions may contain minor BC-breaks.
  • composer require arxy/entity-translations-bundle
  • Register bundle in AppKernel.php: new Arxy\EntityTranslationsBundle\ArxyEntityTranslationsBundle()
  • Translatable must implements \Arxy\EntityTranslationsBundle\Model\Translatable
  • Translations must implements \Arxy\EntityTranslationsBundle\Model\Translation
  • You must have 1 entity containing all the languages, it must implements \Arxy\EntityTranslationsBundle\Language
  • Include services.xml in config.yml:
imports:
    - { resource: "@ArxyEntityTranslationsBundle/Resources/config/services.xml" }

No configuration is needed. Current and fallback locales are taken from Symfony:

Symfony Translations
How to Work with the User's Locale

framework:
    translator:      { fallbacks: ["bg", "de"] }

Example entities:

Language

<?php

namespace Example;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="languages")
 */
class Language implements \Arxy\EntityTranslationsBundle\Model\Language
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer", length=11)
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

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

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     * @return Language
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getLocale(): string
    {
        return $this->locale;
    }

    /**
     * @param mixed $locale
     * @return Language
     */
    public function setLocale($locale)
    {
        $this->locale = $locale;

        return $this;
    }
}

News.php

<?php

namespace Example;

use Doctrine\ORM\Mapping as ORM;
use Arxy\EntityTranslationsBundle\Model\Translatable;
use Arxy\EntityTranslationsBundle\Model\Translation;

/**
 * @ORM\Entity()
 * @ORM\Table(name="news")
 */
class News implements Translatable
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     */
    protected $id;


    /**
     * @ORM\OneToMany(targetEntity="NewsTranslation", mappedBy="translatable", cascade={"ALL"}, orphanRemoval=true)
     */
    protected $translations;

    /**
     * @var NewsTranslation
     */
    private $currentTranslation;
    
    public function getTranslations() 
    {
        return $this->translations;
    }
    
    /**
     * This is important, as form has default option: by_reference = false
     * so here we set the mapped side entity. 
     * @param NewsTranslation|null $translation
     */
    public function addTranslation(NewsTranslation $translation) 
    {
        $this->getTranslations()->add($translation);
        $translation->setTranslatable($this);
    }
    
    /**
     * This is also used by form.
     * @param NewsTranslation|null $translation
     */
    public function removeTranslation(NewsTranslation $translation)
    {
        $this->getTranslations()->removeElement($translation);
    }

    /**
    * This method is used by bundle to inject current translation.
    */
    public function setCurrentTranslation(Translation $translation = null): void
    {
        $this->currentTranslation = $translation;
    }
    
    /**
     * @return string|null 
     */
    public function getTitle()
    {
        return !$this->currentTranslation ?: $this->currentTranslation->getTitle();
    }
}

NewsTranslations.php

<?php

namespace Example;

use Arxy\EntityTranslationsBundle\Model\Language;use Doctrine\ORM\Mapping as ORM;
use Arxy\EntityTranslationsBundle\Model\Translation;

/**
 * @ORM\Entity
 * @ORM\Table(name="news_translations")
 */
class NewsTranslation implements Translation
{

    /**
     * @var News
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="News", inversedBy="translations")
     */
    protected $translatable;

    /**
     * @var Language
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Language")
     */
    protected $language;

    /**
     * @var string
     * @ORM\Column(type="string")
     */
    protected $title;

    /**
     * @return News
     */
    public function getTranslatable()
    {
        return $this->translatable;
    }

    /**
     * @param News $translatable
     */
    public function setTranslatable(News $translatable = null)
    {
        $this->translatable = $translatable;
    }

    /**
     * @return Language
     */
    public function getLanguage(): Language
    {
        return $this->language;
    }

    /**
     * @param Language $language
     */
    public function setLanguage(Language $language)
    {
        $this->language = $language;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }
}

Then you can translate them on yourself

$news = new News();

$englishTranslation = new NewsTranslation();
$englishTranslation->setLanguage($englishLanguage);
$englishTranslation->setTitle('Title on english');
$news->addTranslation($englishTranslation);

$em->persist($news);
$em->flush();

Internal API:

If you wish to change language of all managed entities:

$this->get('arxy.entity_translations.translator')->setLocale('bg');

You can change language of single entity:

$initializedLocale = $this->get('arxy.entity_translations.translator')->initializeTranslation($entity, 'bg');

$initializedLocale is actual locale initialized in entity - it's not necessary to be bg, it could be one of fallback locales. Argument #2 can be either string locale or Language entity.

You can detach entity from manager

$this->get('arxy.entity_translations.translator')->detach($entity);

So it won't be affected by locale changing.

If you wish to get single translation without initialize it, you can use:

/** @var $translation \Arxy\EntityTranslationBundle\Model\Translation */
$translation = $this->get('arxy_entity_translations.translator')->getTranslation($entity, 'bg');

Argument #2 can be either string locale or Language entity.

You can also use translator to translate objects instead of using setCurrentTranslation.

$translation = $this->get('arxy_entity_translations.translator')->translate($entity, 'field', 'bg');

Argument #3 is optional. If omitted current locale is assumed.

You can also use class instead of key for accessing service:

... $this->get(\Arxy\EntityTranslationsBundle\Translator::class) ...

You can also use embedded Twig filters to translate in twig:

{{ news|translate('title')|lower }}
{{ news|translate('title', 'en')|lower }}

or get the whole translation:

{% set translation = news|translation('en') %}
{% if translation %}
  {{ translation.title }}
{% endif %}

Using form to easily translate entities.

doctrine:
   orm:
        # search for the "ResolveTargetEntityListener" class for an article about this
        resolve_target_entities: 
            Arxy\EntityTranslationsBundle\Model\Language: Example\Language

Translatable should have addTranslation, removeTranslation ( see by-reference and How to Work with Doctrine Associations / Relations ):

    public function addTranslation(NewsTranslation $translation)
    {
        if (!$this->translations->contains($translation)) {
            $this->translations->add($translation);
            $translation->setTranslatable($this);
        }
    }


    public function removeTranslation(NewsTranslation $translation)
    {
        $this->translations->removeElement($translation);
        $translation->setTranslatable(null);
    }

Translation should implements EditableTranslation instead of simple Translation

use Arxy\EntityTranslationsBundle\Model\EditableTranslation;

class NewsTranslation implements EditableTranslation

Load form theme (optionally)

twig:
    form_themes:
        - '@ArxyEntityTranslations/bootstrap_4_tab_layout.html.twig'

Use '@ArxyEntityTranslations/bootstrap_3_tab_layout.html.twig' for Bootstrap 3 support.

You need to create translation's form.

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class NewsTranslationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'title',
            TextType::class,
            [
                'required' => false,
                'constraints' => [
                    new NotBlank(),
                    new SomeBulgarianSymbolConstraint([
                        'groups'=> ['bg']
                    ]) // This will be validated only on bg locale
                    new SomeChineseSymbolConstraint([
                        'groups'=> ['zh']
                    ])  // This will be validated only on zh locale
                ],
            ]
        );
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('data_class', NewsTranslation::class); // this is important
        $resolver->setDefault('constraints', [
            new NotNull(
                [
                    'groups' => ['en'], // make only english required
                ]
            ),
        ]);
    }
}

And then you can:

->add(
    'translations',
    \Arxy\EntityTranslationsBundle\Form\Type\TranslationsType::class,
    [
        'entry_type' => NewsTranslationType::class,
        'em' => 'manager_name', // optional
        'query_builder' => function(EntityRepository $repo) {
            return $repo->createQueryBuilder('languages');
        }, // optional
        'entry_language_options' => [
            'en' => [
                'required' => true,
            ]
        ],
    ]
)

in your main form.

It's important to include required in entry_language_options for specific locales, because validation is triggered only when language is not empty or it's required.

Language is assumed as not empty when at least one of the fields are filled in.

arxy/entity-translations-bundle 适用场景与选型建议

arxy/entity-translations-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.28k 次下载、GitHub Stars 达 9, 最近一次更新时间为 2020 年 03 月 16 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「translation」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 arxy/entity-translations-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 arxy/entity-translations-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 arxy/entity-translations-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.28k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 10
  • 点击次数: 8
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 9
  • Watchers: 6
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-03-16