Skip to content

Instantly share code, notes, and snippets.

@lauris
Created December 14, 2012 08:38
Show Gist options
  • Save lauris/4283678 to your computer and use it in GitHub Desktop.
Save lauris/4283678 to your computer and use it in GitHub Desktop.
<?php
namespace Foobar\NewsBundle\Listener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Foobar\NewsBundle\Entity\Item;
use Foobar\NewsBundle\Entity\Subscriber;
/**
* Listener EmailSender
*/
class EmailSender
{
protected $container, $mailer, $entity, $em;
/**
* Set Container and Swift_Mailer
*
* @param ContainerInterface $container
* @param \Swift_Mailer $mailer
*/
public function __construct(ContainerInterface $container, \Swift_Mailer $mailer)
{
$this->container = $container;
$this->mailer = $mailer;
}
/**
* postPersist Event Listener
* Send email after Item is saved
*
* @param LifecycleEventArgs $args
*/
public function postPersist(LifecycleEventArgs $args)
{
$this->entity = $args->getEntity();
$this->em = $args->getEntityManager();
if ($this->entity instanceof Item)
{
$this->sendNewsletters();
}
if ($this->entity instanceof Subscriber)
{
$this->sendConfirmation();
}
}
/**
* Queue newsletters
* Emails are not actually sent from here, a cron task will send from the spool
*/
public function sendNewsletters()
{
$message = \Swift_Message::newInstance()
->setSubject('Newsletter - '.$this->entity->getTitle())
->setFrom('[email protected]')
->setBody($this->container->get('templating')->render(
'FoobarNewsBundle:Email:newsletter.txt.twig',
array("item" => $this->entity)
));
$subscribers = $this->em
->getRepository('FoobarNewsBundle:Subscriber')
->findBy(array("is_active" => true));
foreach($subscribers as $subscriber)
{
$message->setTo($subscriber->getEmail());
$this->mailer->send($message);
}
}
/**
* Send confirmation email
* Emails are not actually sent from here, a cron task will send from the spool
*/
public function sendConfirmation()
{
$message = \Swift_Message::newInstance()
->setSubject('Newsletter Confirmation')
->setFrom('[email protected]')
->setTo($this->entity->getEmail())
->setBody($this->container->get('templating')->render(
'FoobarNewsBundle:Email:confirm.txt.twig',
array("subscriber" => $this->entity)
));
$this->mailer->send($message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment