Skip to content

Instantly share code, notes, and snippets.

@smgladkovskiy
Created September 3, 2014 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smgladkovskiy/a3d98b7c58300200a53d to your computer and use it in GitHub Desktop.
Save smgladkovskiy/a3d98b7c58300200a53d to your computer and use it in GitHub Desktop.
Laravel 4 custom Mailer class to queue mail with i18n content
<?php namespace Site\Mailers;
use Closure;
use Exception;
use I18n;
use Illuminate\Mail\Mailer as Mail;
use Illuminate\Mail\Message;
use Illuminate\Queue\QueueManager;
use Illuminate\Support\SerializableClosure;
use Site\Exceptions\SentMailException;
/**
* Class Mailer
*
* @package Site\Mailers
*/
class Mailer {
/*
* The QueueManager instance.
*
* @var \Illuminate\Queue\QueueManager
*/
private $queue;
/**
* @var Mail
*/
private $mail;
/**
* @param Mail $mail
* @param QueueManager $queue
*/
public function __construct(Mail $mail, QueueManager $queue)
{
$this->mail = $mail;
$this->queue = $queue;
}
/**
* @param $email
* @param $subject
* @param $view
* @param $data
*/
public function sendTo($email, $subject, $view, $data = [])
{
$data = array_merge($data, ['lang' => I18n::getCurrentLocale()]);
try
{
$this->queue(
$view, $data, function (Message $message) use ($email, $subject)
{
$message->to($email)->subject($subject);
});
}
catch(Exception $e)
{
throw new SentMailException($e->getMessage());
}
}
/**
* Queue a new e-mail message for sending.
*
* @param string|array $view
* @param array $data
* @param \Closure|string $callback
* @param string $queue
*
* @return void
*/
public function queue($view, array $data, $callback, $queue = null)
{
$callback = $this->buildQueueCallable($callback);
$this->queue->push('\Site\Mailers\Mailer@handleQueuedMessage', compact('view', 'data', 'callback'), $queue);
}
/**
* Build the callable for a queued e-mail job.
*
* @param mixed $callback
*
* @return mixed
*/
protected function buildQueueCallable($callback)
{
if(!$callback instanceof Closure)
{
return $callback;
}
return serialize(new SerializableClosure($callback));
}
/**
* Handle a queued e-mail message job.
*
* @param \Illuminate\Queue\Jobs\Job $job
* @param array $data
*
* @return void
*/
public function handleQueuedMessage($job, $data)
{
$lang = array_get($data['data'], 'lang');
if($lang)
{
I18n::setLocale($lang);
}
$this->mail->send($data['view'], $data['data'], $this->getQueuedCallable($data));
$job->delete();
}
/**
* Get the true callable for a queued e-mail message.
*
* @param array $data
*
* @return mixed
*/
protected function getQueuedCallable(array $data)
{
if(str_contains($data['callback'], 'SerializableClosure'))
{
return with(unserialize($data['callback']))->getClosure();
}
return $data['callback'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment