php 示例

最后更新于:2022-04-02 04:19:37

[TOC] ## 示例 适配器模式在 PHP 代码中很常见。基于一些遗留代码的系统常常会使用该模式。在这种情况下,适配器让遗留代码与现代的类得以相互合作 ### 概念示例
main.php ``` adaptee = $adaptee; } public function request(): string { return strrev($this->adaptee->specificRequest()); } } function clientCode(Target $target) { echo $target->request(); } $adaptee = new Adaptee(); $adapter = new Adapter($adaptee); clientCode($adapter); ```

输出 ``` Special behavior of the Adaptee. ``` ### 改造邮箱发送接口 适配器允许你使用第三方或遗留系统的类, 即使它们与你的代码不兼容 你可以创建一系列特殊的封装器,来让应用所发出的调用与第三方类所要求的接口与格式适配,而无需重写应用的通知接口以使其支持每一个第三方服务(如钉钉、微信、短信或其他任何服务)
main.php ``` adminEmail = $adminEmail; } public function send(string $title, string $message): void { mail($this->adminEmail, $title, $message); echo "send email :'$title' to '{$this->adminEmail}' that says '$message'."; } } class SlackApi { private $login; private $apiKey; public function __construct(string $login, string $apiKey) { $this->login = $login; $this->apiKey = $apiKey; } public function logIn(): void { echo "logIn :'{$this->login}'.\n"; } public function sendMessage(string $chatId, string $message): void { echo "sendMessage :'$chatId' chat: '$message'.\n"; } } class SlackNotification implements Notification { private $slack; private $chatId; public function __construct(SlackApi $slack, string $chatId) { $this->slack = $slack; $this->chatId = $chatId; } // 对发邮箱接口进行适配 public function send(string $title, string $message): void { // strip_tags 可以去掉原先邮箱发送时候携带的 html标签 $slackMessage = "#" . $title . "# " . strip_tags($message); $this->slack->logIn(); $this->slack->sendMessage($this->chatId, $slackMessage); } } // 假设为老代码的调用通知接口 function clientCode(Notification $notification) { // ... echo $notification->send("发送 title","

发送内容

"); // ... } $notification = new EmailNotification("developers@example.com"); clientCode($notification); echo "\n\n"; $slackApi = new SlackApi("example.com", "XXXXXXXX"); $notification = new SlackNotification($slackApi, "Example.com Developers"); clientCode($notification); ```

输出 ``` Sent email with title '发送 title' to 'developers@example.com' that says '

发送内容

'. logIn :'example.com'. sendMessage :'Example.com Developers' chat: '#发送 title# 发送内容'. ```
';