適配器設計模式是一種結構模式,允許具有不相容介面的物件一起工作。它充當兩個物件之間的中介(或適配器),將一個物件的介面轉換為另一個物件期望的介面。這允許那些因為具有不同介面而不相容的類別在不修改其原始程式碼的情況下進行協作。
適配器結構
適配器模式一般由三個主要元素組成:
適配器類型
何時使用適配器?
此模式在需要使用外部程式庫或 API 的系統中非常有用,讓您在不更改這些程式庫的程式碼的情況下調整其功能。
這裡是如何使用適配器設計模式將 PHPMailer 與自訂介面整合的範例。
情況:
假設您的系統期望任何電子郵件發送類別實現一個名為 IMailer 的接口,但 PHPMailer 並不直接遵循此接口。 Adapter將用於使PHPMailer適應系統期望的介面。
透過 Composer 安裝 PHPMailer
composer require phpmailer/phpmailer
目錄系統
?Adapter ┣ ?src ┃ ┣ ?Interfaces ┃ ┃ ┗ ?IMailer.php ┃ ┣ ?Adapters ┃ ┃ ┗ ?PHPMailerAdapter.php ┃ ┗ ?Services ┃ ┗ ?ServicoDeEmail.php ┣ ?vendor ┣ ?composer.json ┗ ?index.php
自動載入
在composer.json檔案(位於專案根目錄)中,新增App命名空間以自動載入類別:
{ "autoload": { "psr-4": { "App\\": "src/" } }, "require": { "phpmailer/phpmailer": "^6.5" } }
IMailer介面
namespace App\Interfaces; interface IMailer { public function send($to, $subject, $message); }
類別 PHPMailerAdapter
namespace App\Adapters; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; use App\Interfaces\IMailer; class PHPMailerAdapter implements IMailer { private $phpMailer; public function __construct() { $this->phpMailer = new PHPMailer(true); // Basic PHPMailer configuration $this->phpMailer->isSMTP(); $this->phpMailer->Host = 'smtp.example.com'; $this->phpMailer->SMTPAuth = true; $this->phpMailer->Username = '[email protected]'; $this->phpMailer->Password = 'password'; $this->phpMailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $this->phpMailer->Port = 587; $this->phpMailer->setFrom('[email protected]', 'Your Name'); } }
public function send($to, $subject, $message) { try { $this->phpMailer->addAddress($to); $this->phpMailer->Subject = $subject; $this->phpMailer->Body = $message; $this->phpMailer->send(); echo 'Email sent successfully!'; } catch (Exception $e) { echo "Failed to send email: {$this->phpMailer->ErrorInfo}"; } }
類電子郵件服務
namespace App\Services; use App\Interfaces\IMailer; class EmailService { private $mailer; public function __construct(IMailer $mailer) { $this->mailer = $mailer; } }
public function sendEmailToClient($to, $subject, $message) { $this->mailer->send($to, $subject, $message); }
文件index.php
require 'vendor/autoload.php'; use App\Adapters\PHPMailerAdapter; use App\Services\EmailService; // Creating the PHPMailer Adapter $mailer = new PHPMailerAdapter(); // Using the email service with the IMailer interface $emailService = new EmailService($mailer); // Sending an email $emailService->sendEmailToClient('[email protected]', 'Email Subject', 'Message content.');
架構說明
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3