我决定在Symfony上安装"gedmo/doctrine-extensions"
以使用Translatable
。
它工作正常,只是监听器忽略了我指定的默认语言环境,总是回到en_US
。
可翻译作为服务插入:
#config.yml
services:
gedmo.listener.translatable:
class: Gedmo\Translatable\TranslatableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ @annotation_reader ] ]
- [ setDefaultLocale, [ ru ] ]
- [ setTranslationFallback, [ true ] ]
当我尝试在数据库中find()
对象时,它始终会提取en_US
而不是ru
:
$test = $em->find('Vendor\Entity\Test', 1);
//outputs row with 'locale' = "en_US" from `ext_translations_test` table
只有我直接指定语言,例如:
$test->setTranslatableLocale('ru');
$em->refresh($test);
它提供了理想的翻译。
有没有办法设置有效的默认语言环境?
更新
在config.yml
中添加另一个调用函数解决了问题,现在我还不太确定setDefaultLocale()
函数实际上做了什么,因为Gedmo\Translatable\TranslatableListener::$defaultLocale
属性提供了最可怕的评论我曾见过。将尝试找到更多...
services:
gedmo.listener.translatable:
class: Gedmo\Translatable\TranslatableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ @annotation_reader ] ]
- [ setDefaultLocale, [ ru ] ]
- [ setTranslatableLocale, [ ru ] ]
- [ setTranslationFallback, [ true ] ]
答案 0 :(得分:3)
根据:https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/symfony2.md
注意:如果您注意到,如果您使用可记录或可翻译的行为,则需要创建此侦听器类的Acme \ DemoBundle \ Listener \ DoctrineExtensionListener。此侦听器将从请求和用户名使用的语言环境设置为loggable。因此,要完成设置,请创建Acme \ DemoBundle \ Listener \ DoctrineExtensionListener
确保您也设置了内核侦听器。
namespace Acme\DemoBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class DoctrineExtensionListener implements ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
protected $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function onLateKernelRequest(GetResponseEvent $event)
{
$translatable = $this->container->get('gedmo.listener.translatable');
$translatable->setTranslatableLocale($event->getRequest()->getLocale());
}
public function onKernelRequest(GetResponseEvent $event)
{
$securityContext = $this->container->get('security.context', ContainerInterface::NULL_ON_INVALID_REFERENCE);
if (null !== $securityContext && null !== $securityContext->getToken() && $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$loggable = $this->container->get('gedmo.listener.loggable');
$loggable->setUsername($securityContext->getToken()->getUsername());
}
}
}
并将以下内容添加到配置文件中:
services:
extension.listener:
class: Acme\DemoBundle\Listener\DoctrineExtensionListener
calls:
- [ setContainer, [ @service_container ] ]
tags:
# translatable sets locale after router processing
- { name: kernel.event_listener, event: kernel.request, method: onLateKernelRequest, priority: -10 }
# loggable hooks user username if one is in security context
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }