无法从 symfony 4.3.3 中的数据库加载翻译

Cannot load translation from database in symfony 4.3.3

我正在尝试从 Symfony 4 中的数据库加载翻译。Translator 实例不会调用我使用本教程编写的自定义加载器 (https://medium.com/@andrew72ru/store-translation-messages-in-database-in-symfony-3f12e579df74)。

我在 /translation 文件夹 (messages.it.db) 中创建了虚拟文件来触发加载程序,但它没有被调用。

services.yaml

parameters:
    locales: ['it','en']
    db_i18n.entity: App\Entity\Translation
 services:
    translation.loader.db:
        class: App\Loader\DbLoader
        arguments:
          - '@service_container'
          - '@doctrine.orm.entity_manager'
        tags:
          - { name: translation.loader, alias: db}

DbLoader.php

namespace App\Loader;


use Creative\DbI18nBundle\Interfaces\EntityInterface;
use Creative\DbI18nBundle\Interfaces\TranslationRepositoryInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Translation\Loader\LoaderInterface;
use Symfony\Component\Translation\MessageCatalogue;

class DbLoader implements LoaderInterface
{
    /**
     * @var EntityManagerInterface
     */
    private $doctrine;

    /**
     * @var string
     */
    private $entityClass;

    public function __construct(ContainerInterface $container, EntityManagerInterface $doctrine)
    {
        $this->doctrine = $doctrine;
        $this->entityClass = $container->getParameter('db_i18n.entity');
    }

    public function load($resource, $locale, $domain = 'messages')
    {
        $messages = $this->getRepository()->findByDomainAndLocale($domain, $locale);
        $values = array_map(static function (EntityInterface $entity) {
            return $entity->getTranslation();
        }, $messages);

        $catalogue = new MessageCatalogue($locale, [
            $domain => $values
        ]);

        return $catalogue;
    }

    public function getRepository(): TranslationRepositoryInterface
    {
        return $this->doctrine->getRepository($this->entityClass);
    }
}

Here's my translation table

这是我用来调用翻译器的测试代码

TestController.php

class TestController extends AbstractController
{
    /**
     * @Route("/test", name="test")
     */
    public function index(TranslatorInterface $translator)
    {
        $translator->trans('prova', [], 'messages', 'it');

        return new Response();
    }
}

结果应该是"prova it",但我得到的却是"prova",这是翻译的关键。我试图在 DbLoader 构造函数上放置一个 dd(),但它从未被调用过。

我的项目中也有Api平台,但我不认为这是导致这个问题的原因。

我解决了我的问题。

通过在我的 Translator 实例上使用 dd(),我发现 Symfony 没有正确加载我的翻译文件。查看属性,我发现我的翻译文件的路径不正确。

我把它们放在 src/Resources/translations 中,然后它起作用了!