如何从Symfony4中的数据库加载翻译? [英] How to load translations from a database in Symfony4?
问题描述
根据此symfony文档文章应该可以加载您自己的翻译格式.因此,我正在尝试从数据库中加载它们.
According to this symfony documentation article it should be possible to load your own translations format. So I'm trying to load them from the database.
但是我尽一切努力使它起作用.只是没有.
But whatever I try to make this work. It just doesn't.
使用Database Loader是正确的方法还是应该做其他事情以从数据库中加载翻译?
Is using a Database Loader the right way to go or should I do something else to load translations from the database?
App \ Translation \ Loader \ DatabaseLoader.php:
namespace App\Translation\Loader;
use App\Entity\Translation;
use App\Domain\TranslationManagerInterface;
use Symfony\Component\Translation\Loader\LoaderInterface;
use Symfony\Component\Translation\MessageCatalogue;
/**
* Database Loader
*/
class DatabaseLoader implements LoaderInterface
{
/**
* Translation Manager
*
* @var TranslationManagerInterface
*/
private $_translationManager;
/**
* Constructor
*
* @param TranslationManagerInterface $translationManager
*/
public function __construct(TranslationManagerInterface $translationManager)
{
$this->_translationManager = $translationManager;
}
/**
* {@inheritDoc}
*/
public function load($resource, $locale, $domain = 'general')
{
$translations = $this->_translationManager->findByLocaleAndDomain($locale, $domain);
$catalogue = new MessageCatalogue($locale);
/* @var Translation $translation */
foreach($translations as $translation)
{
$catalogue->set(
$translation->getToken(),
$translation->getContent(),
$translation->getDomain()()
);
}
}
}
config/services.yaml:
# database loader
translation.loader.database:
class: 'App\Translation\Loader\DatabaseLoader'
arguments: [ 'App\Domain\TranslationManager' ]
tags:
- { name: translation.loader, alias: database, priority: 100 }
我什至尝试通过内核请求上的事件侦听器将加载程序手动添加到翻译器中.我不想使用完整的捆绑包,因为我已经有一个充满翻译的数据库
I've even tried manually adding the the loader to the translator with a event listener on the kernel request. I don't want to use a full bundle as I already a database filled with translations
推荐答案
我扩展了Translator类,以避免必须为应用程序中的每个域创建一个虚拟翻译文件.
I extended the Translator class to avoid having to create a dummy translation file for every domain in the app.
要覆盖标准的Translator组件,需要加载Compiler Pass.
To override the standard Translator component a Compiler Pass needs to be loaded.
翻译器编译器通行证:
namespace App\DependencyInjection\Compiler;
use App\Domain\TranslationManagerInterface;
use App\Translation\Translator;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class TranslatorCompilerPass implements CompilerPassInterface
{
private $translatorServiceId;
private $readerServiceId;
private $loaderTag;
private $debugCommandServiceId;
private $updateCommandServiceId;
/**
* @param string $translatorServiceId
* @param string $readerServiceId
* @param string $loaderTag
* @param string $debugCommandServiceId
* @param string $updateCommandServiceId
*/
public function __construct(
string $translatorServiceId = 'translator.default',
string $readerServiceId = 'translation.reader',
string $loaderTag = 'translation.loader',
string $debugCommandServiceId = 'console.command.translation_debug',
string $updateCommandServiceId = 'console.command.translation_update'
) {
$this->translatorServiceId = $translatorServiceId;
$this->readerServiceId = $readerServiceId;
$this->loaderTag = $loaderTag;
$this->debugCommandServiceId = $debugCommandServiceId;
$this->updateCommandServiceId = $updateCommandServiceId;
}
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$loaders = [];
$loaderRefs = [];
foreach ($container->findTaggedServiceIds($this->loaderTag, true) as $id => $attributes) {
$loaderRefs[$id] = new Reference($id);
$loaders[$id][] = $attributes[0]['alias'];
if (isset($attributes[0]['legacy-alias'])) {
$loaders[$id][] = $attributes[0]['legacy-alias'];
}
}
if ($container->hasDefinition($this->readerServiceId)) {
$definition = $container->getDefinition($this->readerServiceId);
foreach ($loaders as $id => $formats) {
foreach ($formats as $format) {
$definition->addMethodCall('addLoader', [$format, $loaderRefs[$id]]);
}
}
}
$definition = $container->findDefinition($this->translatorServiceId);
$definition
->setClass(Translator::class)
->replaceArgument(0, null)
->replaceArgument(1, $definition->getArgument(1))
->replaceArgument(2, $definition->getArgument(4)["cache_dir"])
->replaceArgument(3, $definition->getArgument(4)["debug"])
->replaceArgument(4, $definition->getArgument(4)["resource_files"])
->addMethodCall("setTranslationManager", [new Reference(TranslationManagerInterface::class)])
;
if (!$container->hasParameter('twig.default_path')) {
return;
}
if ($container->hasDefinition($this->debugCommandServiceId)) {
$container->getDefinition($this->debugCommandServiceId)->replaceArgument(4, $container->getParameter('twig.default_path'));
}
if ($container->hasDefinition($this->updateCommandServiceId)) {
$container->getDefinition($this->updateCommandServiceId)->replaceArgument(5, $container->getParameter('twig.default_path'));
}
}
}
翻译器类:
namespace App\Translation;
use App\Domain\TranslationManagerInterface;
use App\Entity\Model\Translation\Translation;
use Symfony\Component\Translation\Translator as SymfonyTranslator;
class Translator extends SymfonyTranslator
{
/**
* @var TranslationManagerInterface
*/
private $_translationManager;
/**
* @param TranslationManagerInterface $translationManager
*/
public function setTranslationManager(TranslationManagerInterface $translationManager)
{
$this->_translationManager = $translationManager;
}
/**
* {@inheritdoc}
*/
public function trans($id, array $parameters = [], $domain = null, $locale = null)
{
if (null === $locale && null !== $this->getLocale()) {
$locale = $this->getLocale();
}
if (null === $locale) {
$locale = $this->getFallbackLocales()[0]; // fallback locale
}
// the translation manager automagically creates new translation entries if it doesn't exist yet
$translation = $this->_translationManager->findOneByTokenLocaleAndDomain($id, $locale, $domain);
// check if it exists
if (isset($translation) && null !== $translation && $translation instanceof Translation) {
return strtr($translation->getContent(), $parameters);
}
// fallback
return parent::trans($id, $parameters, $domain, $locale);
}
}
这篇关于如何从Symfony4中的数据库加载翻译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!