Last active
August 29, 2015 13:57
-
-
Save DracoBlue/9468262 to your computer and use it in GitHub Desktop.
Very simple but fast (file based) mail queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MailQueueService() | |
{ | |
public function getMailsFolder() | |
{ | |
return '/tmp/mails/'; | |
} | |
public function popSpooledMail() | |
{ | |
foreach (new DirectoryIterator($this->getMailsFolder()) as $file_info) { | |
if($file_info->isDot()) continue; | |
if ($file_info->getExtension() == 'json') | |
{ | |
$file_path = $file_info->getPathname(); | |
$content = @file_get_contents($file_path); | |
if ($content) | |
{ | |
if (@unlink($file_path)) | |
{ | |
return json_decode($content, true); | |
} | |
} | |
} | |
} | |
throw new \Exception('No mail in the queue!'); | |
} | |
public function pushMail($values) | |
{ | |
file_put_contents($this->generateUniqueFileNameForSpooledMail(), json_encode($values)); | |
} | |
protected function generateUniqueFileNameForSpooledMail() | |
{ | |
$uuid = substr(sha1(uniqid('', true) . microtime(true)), 0, 32); | |
$file_name = $this->getMailsFolder() . $uuid . '.json'; | |
while (file_exists($file_name)) | |
{ | |
$uuid = substr(sha1(uniqid('', true) . microtime(true)), 0, 32); | |
$file_name = $this->getMailsFolder() . $uuid . '.json'; | |
} | |
return $file_name; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$queue = new \MailQueueService(); | |
$queue->pushMail(array('subject' => 'hai', 'body' => 'hai body', 'email' => 'hans@example.org')); | |
$queue->pushMail(array('subject' => 'hai2', 'body' => 'hai body', 'email' => 'hans@example.org')); | |
$queue->pushMail(array('subject' => 'hai3', 'body' => 'hai body', 'email' => 'hans@example.org')); | |
$count = 5; | |
try | |
{ | |
while ($count > 0) | |
{ | |
$mail_values = $queue->popSpooledMail(); | |
/* FIXME: code to send the mail values */ | |
$count--; | |
} | |
} catch (\Exception $exception) | |
{ | |
/* done! */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment