Learn about the adapter pattern in PHP in one article
In the previous article " A Brief Talk on the Decorator Mode in PHP" we introduced the decorator mode in PHP. This article will take you to understand the adapter mode in PHP.
There has always been a classic example of this model, and that is the socket! That's right, when we buy electrical appliances from abroad, or travel abroad on business, we often need a power adapter, because our country's voltage standard is 220 volts, while other countries have 110 volt standards. And this power adapter is a symbol of adapter mode. When the object does not meet the requirements, add an adapter to it! !
Gof class diagram and explanation
GoF definition: Convert the interface of a class into another interface that the customer wants. The Adapter pattern enables classes that originally could not work together due to incompatible interfaces to work together
GoF class diagram:
Inheritance
Combined
Code implementation
interface Target{ function Request() : void; }
Define an interface contract, It can also be a normal class with implementation methods (we will use classes in the following examples)
class Adapter implements Target{ private $adaptee; function __constuct($adaptee){ $this->adaptee = $adaptee; } function Request() : void { $this->adaptee->SpecificRequest(); } }
The adapter implements this interface contract so that the Request() method can be implemented, but please note that what we actually call It is a method in the Adaptee class
class Adaptee { function SpecificRequest() : void{ echo "I'm China Standard!"; } }
- The adapter has two forms. The class diagram above is given. The
- inheritance form of the combined form implemented by our code is in the GoF book. C is used as an example, because C can implement multiple inheritance, but most of the popular languages are in the form of interfaces, which can also be implemented, but there are not many adapters using this form.
- In fact, it is still oriented to A kind of thinking in interface programming is similar to the packaging of old functions by decorators. Here we directly replace them, but the external calls remain the same
- The adapter mode is actually easy to understand, and the code is really That's all
Let's talk about my mobile phone factory again. This time our business has really grown! It has been sold to Thailand, Singapore, and Indonesia. Anyway, we can be found wherever there is curry. It is said that we produced a curry color. The change of shell is not entirely due to the influence of Noah, but after long-term research, we found that different colors will sell better in different places. Therefore, Foxconn installed a spraying adapter (adapter) for us on the original mobile phone case production line (Target). When we need cases of other colors, we only need this adapter to change different paints (adaptee) , directly install this sprayer, and a new color mobile phone is born. When expanding our business to another country, we can just change the paint. If it takes too long, we will also replace the nozzle (remember the continuous supply of the printer)
Full code :Adapter pattern
https://github.com/zhangyue0503/designpatterns-php/blob/master/05.adapter/source/adapter.php
Example
Continue to send text messages and see when I can compile it~~~
Everyone often uses the SDK provided by these platforms when connecting to information and payment interfaces. Especially with Composer, it is more convenient to install the SDK. However, there is another serious problem. Although the SDKs made by these people have similar functions, their names are very different! ! Our system has always used Alibaba Cloud's services, but this time we need to add the information functions of Jiguang and Baidu Cloud, first as a backup, and secondly, to use different interfaces according to different services to achieve security or economical purposes. Is there any way? Unify their external interfaces so that when we use their SDK, it can be very convenient and the same as the Alibaba Cloud interface that everyone is already used to? Of course, just give them each an adapter. When instantiating, you can just set up an external factory to return different adapters. As long as the implementation method in the adapter is the same as Alibaba Cloud, it will be OK!
SMS sending class diagram
Complete source code: SMS sending adapter method
https:/ /github.com/zhangyue0503/designpatterns-php/blob/master/05.adapter/source/adapter-message.php
<?php class Message{ public function send(){ echo "阿里云发送短信!" . PHP_EOL; } public function push(){ echo "阿里云发送推送!" . PHP_EOL; } } class JiguangSDKAdapter extends Message{ private $message; public function __construct($message){ $this->message = $message; } public function send(){ $this->message->send_out_msg(); } public function push(){ $this->message->push_msg(); } } class JiguangMessage{ public function send_out_msg(){ echo "极光发送短信!" . PHP_EOL; } public function push_msg(){ echo "极光发送推送!" . PHP_EOL; } } class BaiduYunSDKAdapter extends Message{ private $message; public function __construct($message){ $this->message = $message; } public function send(){ $this->message->transmission_msg(); } public function push(){ $this->message->transmission_push(); } } class BaiduYunMessage{ public function transmission_msg(){ echo "百度云发送短信!" . PHP_EOL; } public function transmission_push(){ echo "百度云发送推送!" . PHP_EOL; } } $jiguangMessage = new JiguangMessage(); $baiduYunMessage = new BaiduYunMessage(); $message = new Message(); // 原来的老系统发短信,使用阿里云 $message->send(); $message->push(); // 部分模块用极光发吧 $jgAdatper = new JiguangSDKAdapter($jiguangMessage); $jgAdatper->send(); $jgAdatper->push(); // 部分模块用百度云发吧 $bdAatper = new BaiduYunSDKAdapter($baiduYunMessage); $bdAatper->send(); $bdAatper->push();
Description:
- In this example, we have two adapters, because there are two SDKs that we need to adapt. Who says there can only be one power converter, what if some magical country uses 500 volts? , so it’s better to bring an extra power converter
- Here we inherit the Message class, because the Message class is code that has been written before, and there may be some public methods in it, so there is no interface. abstract. You can consider extracting an abstract interface when refactoring the code, but here it is just to demonstrate that the adapter may not only be able to target the interface. As long as it is consistent with the original object, it is okay not to inherit anything. After all, we are a weakly typed language. , if it is a strong type similar to Java, then inheritance or implementation is still necessary (polymorphism)
- Combined adapters are similar to decorators in that they maintain an external object, and decorators have more The methods in the original class will be used to add functions, while the adapter rarely adds functions. Instead, it directly replaces the Filesystem module in
- Laravel. There is a FilesystemAdapter class. I think There’s nothing more to say. It’s obvious to everyone that we use the adapter pattern. Study it carefully.
- When you want to use a class, but the content it provides does not match your business. ; Or if you want to create a class that can work together with other unrelated classes or unforeseen classes, you might as well try the adapter pattern
Recommended learning: "PHP Video Tutorial 》
The above is the detailed content of Learn about the adapter pattern in PHP in one article. 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

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
