Skip to content

Instantly share code, notes, and snippets.

@turbo-ele
Created July 23, 2015 11:51
Show Gist options
  • Save turbo-ele/35f3c68d37d70f658585 to your computer and use it in GitHub Desktop.
Save turbo-ele/35f3c68d37d70f658585 to your computer and use it in GitHub Desktop.
Symfony2 Newsletter Manager
<?php
namespace Acme\Bundle\NewsletterBundle\Manager;
use Symfony\Component\HttpFoundation\Session\Session;
class NewsletterManager
{
/**
* @var \Swift_Mailer
*/
private $mailer;
/**
* @var array
*/
private $recipients;
/**
* @var Session
*/
private $session;
/**
* @var string
*/
private $mailFrom;
/**
* @param \Swift_Mailer $mailer
*/
public function __construct(\Swift_Mailer $mailer, Session $session)
{
$this->mailer = $mailer;
$this->session = $session;
// load recipients
$this->recipients = [];
if ($session->has('newsletter_recipients')) {
$this->recipients = $session->get('newsletter_recipients');
}
// this should actually be set in config
$this->mailFrom = 'you@example.com';
}
/**
* Subscribes a recipient for newsletter.
*
* @param string $emailAddress
*
* @return bool
*/
public function subscribe($emailAddress)
{
if (array_search($emailAddress, $this->recipients) === false) {
$this->recipients[] = $emailAddress;
$this->session->set('newsletter_recipients', $this->recipients);
return true;
}
return false;
}
/**
* Unsubscribes recipient from newsletter.
*
* @param string $emailAddress
*
* @return bool
*/
public function unsubscribe($emailAddress)
{
$index = array_search($emailAddress, $this->recipients);
if ($index !== false) {
unset($this->recipients[$index]);
$this->session->set('newsletter_recipients', $this->recipients);
return true;
}
return false;
}
/**
* Sends a newsletter message to all registered recipients.
*
* @param string $subjectString
* @param string $messageString
*/
public function sendNewsletter($subjectString, $messageString)
{
// send mail to each subscribed email
foreach ($this->getRecipients() as $recipient) {
$message = new \Swift_Message($subjectString, $messageString);
$message->setFrom($this->mailFrom);
$message->setTo($recipient);
$this->mailer->send($message);
}
}
/**
* Return all recipients of a newsletter.
*
* @return array
*/
private function getRecipients()
{
return $this->recipients;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment