简体   繁体   中英

symfony2: how to use translator in console command

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!

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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM