替换 Symfony 3 中的 Translator 服务 [英] Replacing the Translator service in Symfony 3

查看:13
本文介绍了替换 Symfony 3 中的 Translator 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 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: MyBundleTwigTranslationExtension

类看起来像这样:

namespace MyBundleTwigTranslationExtension;

use SymfonyBundleFrameworkBundleTranslationTranslator 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:     AppBundleDecoratingTranslator
    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆