Evdv Evdv - 1 year ago 203
PHP Question

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:

translator.class: MyBundle\Twig\TranslationExtension

The class looks like this:

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

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

Answer Source

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.

    class:     AppBundle\DecoratingTranslator
    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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download