Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2: how to use translator in console command

Tags:

php

symfony

I'm trying to use translator in symfony2 (2.3.0) console command, but I can't make it work. Here is what I've done so far:

use Symfony\Component\Translation\IdentityTranslator;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SendMessageCommand extends ContainerAwareCommand
{
    protected function configure() {
        $this->setName('mycommand:sendmessage')->setDescription('send message.');
    }

    protected function execute(InputInterface $input, OutputInterface $output) {
        $translator = $this->getContainer()->get('translator');

        echo $translator->trans('my.translation.key'); // not working
    }
}

my.translation.key is exists in messages.yml. Any idea how to make it work?

thanks!

like image 646
ihsan Avatar asked Feb 16 '23 12:02

ihsan


1 Answers

I just found that in symfony2 console command, the default locale defined in config.yml is never used so the locale is NULL. So the translator will never use any translations locale available. That's why the translation key is returned intact instead of the translation.

I got this hint when I run only the console command which is trying to translate something, but the catalogue in app/cache/dev/translations folder is not generated.

So, this is how I do to make translations in console command works (in my case, I set it to id_ID):

$translator = $this->getContainer()->get('translator');
$translator->setLocale("id_ID");

echo $translator->trans('my.translation.key'); // works fine! :)

Hope that could help anyone facing the same problem. :)

like image 155
ihsan Avatar answered Feb 24 '23 18:02

ihsan