symfony2.7 pass translator in service container

craphunter picture craphunter · Oct 17, 2015 · Viewed 10.9k times · Source

In symfony 2.3 it was this line in service.yml to get to the translator

In service.yml

arguments: [@translator,....

in serviceFunctions.php

 public function __construct(Translator $translator,...) {
    $this->translator = $translator;

Now I get the error:

must be an instance of Symfony\Component\Translation\Translator, instance of Symfony\Component\Translation\DataCollectorTranslator given

How can I get to the service in 2.7 in dev also in production mode?

Answer

Mahdi Trimech picture Mahdi Trimech · Oct 17, 2015

Try to folow this steps :

Class:

use Symfony\Component\Translation\TranslatorInterface;

public function __construct(TranslatorInterface $translator) {
    $this->translator = $translator;
}

public function yourFunction(){
    $this->translator->trans('key', array(), 'yourDomain');
}

Service:

yourService:
        class: yourClass
        arguments: [@translator]
        tags:
            - { name : kernel.event_listener, event: kernel.request, method: yourFunction }

I use this in my code and it's work ;)