symfony2:如何在console命令中使用翻译器

ihs*_*san 4 php symfony

我正在尝试在symfony2(2.3.0)控制台命令中使用翻译器,但我无法使其工作.这是我到目前为止所做的:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

my.translation.key在messages.yml中存在.知道如何让它工作吗?

谢谢!

ihs*_*san 8

我刚刚发现在symfony2 console命令中,config.yml从未使用过定义的默认语言环境,因此语言环境是NULL.因此,翻译人员永远不会使用任何可用的翻译区域设置.这就是为什么翻译键完整而不是翻译返回的原因.

当我只运行试图翻译某些内容的控制台命令时,我得到了这个提示,但是没有生成app/cache/dev/translations文件夹中的目录.

所以,这就是我在控制台命令工作中进行翻译的方式(在我的例子中,我将其设置为id_ID):

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

echo $translator->trans('my.translation.key'); // works fine! :)
Run Code Online (Sandbox Code Playgroud)

希望可以帮助任何人面对同样的问题.:)