Today, I am implementing a Mail Service class using the Singleton Design Pattern in PHP. In many applications, there are frequent email-sending operations, like on an e-commerce website, where an email is sent to the user after they place an order.
Using a Singleton pattern here allows the application to create only a single instance of the mail service connection. This enhances application performance by ensuring only one connection instance is maintained.
Please see the code below:
// Chúng ta có thể cấu hình namespace cho ok hơn, vì mình test nên để require_once đến thư viện
require_once "../../../vendor/autoload.php";
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
class MailService{
private static $instance = null;
private $transport = null;
private $mail_from = ""; // email
private $pass = ""; // password
private $mailer = null;
private function __construct(){
try {
$this->transport =Transport::fromDsn("smtp://{$this->mail_from}:{$this->pass}@smtp.gmail.com:587?encryption=tls");
$this->mailer = new Mailer($this->transport);
} catch (\PDOException $e) {
throw new Exception($e->getMessage());
}
}
public static function getInstance(){
if(self::$instance === null){
// begin create instance
self::$instance = new MailService();
}
// create instance object
return self::$instance;
}
public function sendEmail(Array $data) : Array{
try {
$email = new Email();
$email->from($this->mail_from);
$email->to($data['email']);
$email->subject($data['subject']);
$email->text($data['message']);
if($data['file'] != null){
$email->attachFromPath($data['file']);
}
$this->mailer->send($email);
$data['status'] = 'success';
return json_decode(json_encode($data), true, 512, JSON_THROW_ON_ERROR);
}
catch (\Exception $e) {
$data['status'] = 'error';
$data['message'] = $e->getMessage();
return json_decode(json_encode($data), true, 512, JSON_THROW_ON_ERROR);
}
}
}
Great! Now that the Singleton pattern is set up for the Mail Service, we can use it in our application. Here’s how you can integrate and use the Mail Service Singleton:
$mail = MailService::getInstance();
$mail2 = MailService::getInstance();
var_dump($mail === $mail2); //true
$mail->sendEmail([
'subject' => 'LẬP TRÌNH WEBSITE | HOANGUYENIT',
'email' => 'example@example.com',
])
"You can connect with me on TikTok, YouTube, or my Facebook Fanpage"
"I always share programming knowledge there, so feel free to follow me if you're interested!"
Top comments (1)
Great guide or else you can use PO Box address service to automate your process. Your mail will be handled discreetly and efficiently by our team of highly experienced mail managers.