10

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?

Federkun
  • 36,084
  • 8
  • 78
  • 90
craphunter
  • 961
  • 2
  • 13
  • 34
  • 4
    Possible duplicate of http://stackoverflow.com/questions/29162346/symfony-loggingtranslator-vs-translator – Carlos Granados Oct 17 '15 at 15:41
  • None of the answers below are right, go to the link of the duplicate question to find the answer – Carlos Granados Oct 17 '15 at 22:12
  • 1
    Following the answer in the duplicate question link will defeat the object of having a debug environment as you will never be able to use the debug version of any of the services. Only allowing you to insert a specific service when an interface will guarantee that you will have the correct methods is ridiculous. You sir, are doing it wrong. – qooplmao Oct 19 '15 at 09:53
  • Using the "translator.default" service will disable the new translation logging feature of Symfony 2.6 so no, it's not what you want to do. Use the TranslatorInterface as recommended in all the answers. @CarlosGranados please fix your downvotes. – Derek Dec 17 '15 at 11:42

2 Answers2

20

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

A.L
  • 10,259
  • 10
  • 67
  • 98
Mahdi Trimech
  • 341
  • 1
  • 7
6

Try using the interface rather than the actual translator class. By using interfaces as type hint you can use anything as long as it fits the interface, for instance you could pass in a debug translator in development with a regular one in production without needing to change your code.

use Symfony\Component\Translation\TranslatorInterface;

...

public function __construct(TranslatorInterface $translator)
{
    $this->translator = $translator;
}
qooplmao
  • 17,622
  • 2
  • 44
  • 69