How can one create a wrapper in PHP to handle both PHPMailer and SwiftMailer for email functionalities in a unified way?

To create a wrapper in PHP to handle both PHPMailer and SwiftMailer for email functionalities in a unified way, you can create a class that abstracts the email sending process and allows you to switch between the two libraries easily. This wrapper class can have methods for setting the email content, recipients, attachments, etc., and a method for sending the email using the selected library.

<?php

class EmailWrapper {
    private $mailer;

    public function __construct($library) {
        if($library == 'phpmailer') {
            require_once 'path/to/PHPMailer/PHPMailer.php';
            $this->mailer = new PHPMailer\PHPMailer\PHPMailer();
        } elseif($library == 'swiftmailer') {
            require_once 'path/to/swiftmailer/lib/swift_required.php';
            $transport = new Swift_SmtpTransport('localhost', 25);
            $this->mailer = new Swift_Mailer($transport);
        } else {
            throw new Exception('Unsupported mailer library');
        }
    }

    public function setSubject($subject) {
        $this->mailer->Subject = $subject;
    }

    public function setBody($body) {
        $this->mailer->Body = $body;
    }

    public function setFrom($email, $name) {
        $this->mailer->setFrom($email, $name);
    }

    public function addRecipient($email, $name) {
        $this->mailer->addAddress($email, $name);
    }

    public function addAttachment($file) {
        $this->mailer->addAttachment($file);
    }

    public function send() {
        return $this->mailer->send();
    }
}

// Example of how to use the EmailWrapper class
$email = new EmailWrapper('phpmailer');
$email->setFrom('sender@example.com', 'Sender');
$email->addRecipient('recipient@example.com', 'Recipient');
$email->setSubject('Test Email');
$email->setBody('This is a test email.');
$email->send();

?>