PHP Design Pattern: Adapter
The Adapter Design Pattern is a structural pattern that allows objects with incompatible interfaces to work together. It acts as an intermediary (or adapter) between two objects, converting the interface of one object to the interface expected by the other. This allows classes that would otherwise be incompatible because they have different interfaces to cooperate without modifications to their original code.
Adapter Structure
The Adapter pattern is generally composed of three main elements:
- Client: The class that expects to work with objects of a specific interface.
- Adaptee: The class that has an interface that is incompatible with the client, but whose functionalities are necessary.
- Adapter: The class that implements the interface expected by the client and converts calls to the Adaptee interface.
Types of Adapters
- Object Adapter: Composition-based. The Adapter contains an instance of the class it is adapting.
- Class Adapter: Inheritance-based (usually in languages that support multiple inheritance).
When to use the Adapter?
- When you want to use an existing class, but its interface does not match what the client expects.
- To integrate new functionality into a legacy system, without having to modify the old code.
This pattern is useful in systems that need to work with external libraries or APIs, allowing you to adapt their functionality without changing the code of these libraries.
Example Using PHPMailer
Here is an example of how to use the Adapter Design Pattern to integrate PHPMailer with a custom interface.
Situation:
Let's assume that your system expects any email sending class to implement an interface called IMailer, but PHPMailer does not follow this interface directly. The Adapter will be used to adapt PHPMailer to the interface expected by the system.
Install PHPMailer via Composer
composer require phpmailer/phpmailer
Directory System
?Adapter ┣ ?src ┃ ┣ ?Interfaces ┃ ┃ ┗ ?IMailer.php ┃ ┣ ?Adapters ┃ ┃ ┗ ?PHPMailerAdapter.php ┃ ┗ ?Services ┃ ┗ ?ServicoDeEmail.php ┣ ?vendor ┣ ?composer.json ┗ ?index.php
Autoload
In the composer.json file (located at the root of the project), add the App namespace to automatically load the classes:
{ "autoload": { "psr-4": { "App\": "src/" } }, "require": { "phpmailer/phpmailer": "^6.5" } }
Interface IMailer
namespace App\Interfaces; interface IMailer { public function send($to, $subject, $message); }
Class 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 = 'your-email@example.com'; $this->phpMailer->Password = 'password'; $this->phpMailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $this->phpMailer->Port = 587; $this->phpMailer->setFrom('your-email@example.com', 'Your Name'); } }
- Method send
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}"; } }
Class EmailService
namespace App\Services; use App\Interfaces\IMailer; class EmailService { private $mailer; public function __construct(IMailer $mailer) { $this->mailer = $mailer; } }
- Method sendEmailToClient
public function sendEmailToClient($to, $subject, $message) { $this->mailer->send($to, $subject, $message); }
File index.php
composer require phpmailer/phpmailer
Explanation of the Structure
- IMailer.php: Defines the IMailer interface that any email system should implement.
- PHPMailerAdapter.php: Adapts PHPMailer to the IMailer interface.
- EmailService.php: Email service that uses the IMailer interface to send emails.
- index.php: Main file that uses the email service to send a message.
The above is the detailed content of PHP Design Pattern: Adapter. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
