Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2.7 pass translator in service container

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?

like image 302
craphunter Avatar asked Oct 17 '15 15:10

craphunter


2 Answers

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

like image 52
Mahdi Trimech Avatar answered Nov 03 '22 16:11

Mahdi Trimech


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;
}
like image 33
qooplmao Avatar answered Nov 03 '22 15:11

qooplmao