Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

php - Replacing the Translator service in Symfony 3

In my Symfony 2.8 project I have an extension that adds some extra logic to the trans method:

parameters:
    translator.class: MyBundleTwigTranslationExtension

The class looks like this:

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);
    }
}

Now, I'm migrating to Symfony 3, where those class parameters are deprecated, but how can I implement this by overwriting the translator service?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

See documentation about decorating here: http://symfony.com/doc/current/service_container/service_decoration.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...