2012-09-13 39 views
26

我需要从symfony2的命令类渲染一个树枝模板。从symfony2的命令行发送邮件

namespace IT\bBundle\Command; 

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; 
use Symfony\Component\Console\Input\InputArgument; 
use Symfony\Component\Console\Input\InputInterface; 
use Symfony\Component\Console\Input\InputOption; 
use Symfony\Component\Console\Output\OutputInterface; 

class CronCommand extends ContainerAwareCommand 
{ 
    protected function configure() 
    { 
     $this 
      ->setName('send:emails') 
      ->setDescription('Envio programado de emails'); 
    } 

    protected function execute(InputInterface $input, OutputInterface $output) 
    { 
     $message = \Swift_Message::newInstance() 
      ->setSubject('bla bla') 
      ->setFrom('[email protected]') 
      ->setTo('[email protected]') 
      ->setCharset('UTF-8') 
      ->setContentType('text/html')  
      ->setBody($this->renderView('mainBundle:Email:default.html.twig')); 

     $this->getContainer()->get('mailer')->send($message); 
     $output->writeln('Enviado!'); 
    } 
} 

但是,当我执行命令php app/console send:emails我收到以下错误:

Fatal error: Call to undefined method IT\bBundle\Command\CronCommand::renderView()

我如何渲染视图?

+0

只是一个脚注:如果你打算发送批量电子邮件,这是不是做到这一点。如果它只是一段时间,它会没事的。 – transilvlad

回答

73

这是因为的RenderView是类控制器的方法。而不是那个尝试:

$this->getContainer()->get('templating')->render(...); 
18

变化

​​

$this->getContainer()->get('templating')->render() 
8

也许,不完全是你问的问题,但肯定 - 重要的。

请记住,如果你想通过Command调用发送邮件,你需要flushQueue。

$mailer = $container->get('mailer'); 
$spool = $mailer->getTransport()->getSpool(); 
$transport = $container->get('swiftmailer.transport.real'); 
$spool->flushQueue($transport); 
+0

谢谢Dawid。 – olegsv