symfony translation by using keys

佐手、 提交于 2019-12-04 18:32:56

According to docs you need to register a service in order to load translations from other source like from database

You can also store translations in a database, or any other storage by providing a custom class implementing the LoaderInterface interface. See the translation.loader tag for more information.Reference

What i have done,i have a translation bundle where my translation entity resides so i have registered a service in config.yml and passed doctrine manager @doctrine.orm.entity_manager in order to get data from entity

services:

    translation.loader.db:
        class: Namespace\TranslationBundle\Loader\DBLoader
        arguments: [@doctrine.orm.entity_manager]
        tags:
            - { name: translation.loader, alias: db}

In DBLoader class i have fetched translations from database and sets as mentioned in docs translation.loader

My Loader class

namespace YourNamespace\TranslationBundle\Loader;

use Symfony\Component\Translation\Loader\LoaderInterface;
use Symfony\Component\Translation\MessageCatalogue;
use Doctrine\ORM\EntityManager;

class DBLoader implements LoaderInterface{
    private $transaltionRepository;
    private $languageRepository;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager){

        $this->transaltionRepository = $entityManager->getRepository("YourNamespaceTranslationBundle:LanguageTranslation");
        $this->languageRepository = $entityManager->getRepository("YourNamespaceTranslationBundle:Language");
    }

    function load($resource, $locale, $domain = 'messages'){
        //Load on the db for the specified local

        $language = $this->languageRepository->findOneBy( array('locale' => $locale));

        $translations = $this->transaltionRepository->getTranslations($language, $domain);

        $catalogue = new MessageCatalogue($locale);


        /**@var $translation YourNamespace\TranslationBundle\Entity\LanguageTranslation */
        foreach($translations as $translation){
            $catalogue->set($translation->getLanguageToken(), $translation->getTranslation(), $domain);
        }        
        return $catalogue;
    }
}

Note: Each time you create a new translation resource (or install a bundle that includes a translation resource), be sure to clear your cache so that Symfony can discover the new translation resources: php app/console cache:clear

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!