2012-09-13 42 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