donglu2761 2014-07-25 13:27
浏览 35


I'm using the mailing library from zend framework 2, and also I'm using the translator functionality. But the translations only work inside the template .phtml, and not work in the service function for send the email, for example in translating the subject of the email. This is my code inside my service function to send an email:

$mailFactory = $this->getDependency('mail');
$viewModel = new ViewModel(array(
    'variable' => $x
$message = $mailFactory->prepareMessage($viewModel);
    ->addHeaderLine('MIME-Version', '1.0')
    ->addHeaderLine('Content-type', 'text/html; charset=UTF-8');
$message->setSubject($this->translate('Recover your password'));
$message->addTo($email, $fullname);
$transport = $mailFactory->getTransport();

return $transport->send($message);

The function $this->translate('...') calls to a class that call this code: return $this->translator->translate($text), this works well in all my application, but only works wrong when I send any email (with an exception of the template.phtml, inside this file the translator works well). All my mails received, have the subject in english (not translated) and the content in spanish (translated)

  • 写回答

1条回答 默认 最新

  • dqvtm82066 2014-07-25 14:08

    You have to pass the translator to the service to use it.

    So in your module.config.php under the service_manager key you can do it with a factory or an initializer.


    'service_manager' => array(
        'factories' => array(
            'YourNamespace\YourMailService' => function ($serviceManager) {
                $mailService = new YourNamespace\YourMailService();
                return $mailService;

    You need the method setTranslator in your service class!


    'service_manager' => array(
        'initializers' => array(
            function ($instance, $sm)
                if ($instance instanceof \YourNamespace\TranslatorAwareInterface) {

    With an initializer you need the interface TranslatorAwareInterface:

    namespace YourNamespace;
    use Zend\Mvc\I18n\Translator;
    interface TranslatorAwareInterface
        public function setTranslator(Translator $translator);

    And your service need to implement that interface:

    class YourMailService implements TranslatorAwareInterface
        protected $translator;
        public function setTranslator(Translator $translator)
            $this->translator = $translator;

    In both cases you can use the translator like:

    $message->setSubject($this->translator->translate('Recover your password'));
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 GIS土地利用预测FLUS模型
  • ¥15 visual studio code打不出来中文双引号
  • ¥20 关于#matlab#的问题:ps:完美符合要求有打赏(相关搜索:自适应)
  • ¥15 声音感应灯,问题出在哪里
  • ¥15 关于#matlab#的问题:(0,0)上的贝塞尔曲线,0)上的贝塞尔曲线,并使用自适应积分计算其从t=0到不大于1的任意值区间的弧长
  • ¥20 关于#r语言#rda分析作图的问题,请各位专家解答!
  • ¥50 找回 股票行情系统的资源问题
  • ¥15 gwas 分析-plink 检查人口分层出现下面问题
  • ¥15 关于#matlab#的问题:需要 MATLAB 运行程序,对比四个多址通信方式(TDMA,FDMA,CDMA,OFDMA)的抗噪声性能
  • ¥15 有没有复现过PFENet的,如何解决?