symfony2.7 pass translator in service container symfony2.7 pass translator in service container symfony symfony

symfony2.7 pass translator in service container


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


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