替换Symfony 3中的Translator服务 [英] Replacing the Translator service in Symfony 3
问题描述
在我的Symfony 2.8项目中,我有一个扩展,为 trans 方法添加了一些额外的逻辑:
In my Symfony 2.8 project I have an extension that adds some extra logic to the trans method:
parameters:
translator.class: MyBundle\Twig\TranslationExtension
该类如下:
namespace MyBundle\Twig\TranslationExtension;
use Symfony\Bundle\FrameworkBundle\Translation\Translator as BaseTranslator;
class TranslationExtension extends BaseTranslator
{
private $currentLocale;
public function trans($id, array $parameters = array(), $domain = null, $locale = null)
{
$translation = parent::trans($id, $parameters, $domain, $locale);
// Some extra logic here
return $translation;
}
public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
{
return parent::transChoice($id, $number, $parameters, $domain, $locale);
}
}
现在,我要迁移到不推荐使用那些类参数的Symfony 3,但是如何通过覆盖 translator 服务来实现这一点?
Now, I'm migrating to Symfony 3, where those class parameters are deprecated, but how can I implement this by overwriting the translator service?
推荐答案
与其扩展,不如装饰translator
服务.现在,您覆盖了类名,这也将覆盖其他要装饰服务的包.而且我发现您是因为Twig对其进行了扩展,原始的Twig {{ trans() }}
过滤器也将使用修饰的服务.
Instead of extending, it would be better to decorate the translator
service. Right now you overriding the class name, which will also override other bundles that want to decorate the service. And I see you made it an extension because of Twig, the original Twig {{ trans() }}
filter will use the decorated service too.
services:
app.decorating_translator:
class: AppBundle\DecoratingTranslator
decorates: translator
arguments: ['@app.decorating_translator.inner'] # original translator
public: false
在此处查看有关装饰的文档: http://symfony.com/doc/current/service_container/service_decoration.html
See documentation about decorating here: http://symfony.com/doc/current/service_container/service_decoration.html
这篇关于替换Symfony 3中的Translator服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!