目錄
真實世界範例
概念範例
index.php:  概念範例
#Output.txt:  執行結果
首頁 後端開發 php教程 詳述PHP適配器模式(附程式碼範例)

詳述PHP適配器模式(附程式碼範例)

Apr 05, 2023 pm 03:36 PM
php 後端 適配器

這篇文章為大家帶來了關於php的相關知識,其中主要跟大家聊一聊PHP適配器模式,還有程式碼範例,有興趣的朋友下面一起來看一下吧,希望對大家有幫助。

詳述PHP適配器模式(附程式碼範例)

PHP 適配器模式解說與程式碼範例

適配器是一種結構型設計模式, 它能使不相容的對象能夠相互合作。

適配器可擔任兩個物件間的封裝器, 它會接收對於一個物件的調用, 並將其轉換為另一個物件可識別的格式和介面。

複雜度:******

流行度:******

使用範例: 適配器模式在PHP 程式碼中很常見。 基於一些遺留程式碼的系統常常會使用該模式。 在這種情況下, 適配器讓遺留程式碼與現代的類別得以相互合作。

識別方法: 適配器可以透過以不同抽像或介面類型實例為參數的建構子來識別。 當適配器的任何方法被呼叫時, 它會將參數轉換為適當的格式, 然後將呼叫導向至其封裝物件中的一個或多個方法。

  • 真實世界範例

適配器允許你使用第三方或遺留系統的類, 即使它們與你的程式碼不相容。例如, 你可以建立一系列特殊的封裝器, 來讓應用程式所發出的呼叫與第三方類別所要求的介面與格式適配, 而無需重寫應用程式的通知介面以使其支援每個第三方服務(如釘釘、 微信、 簡訊或其他任何服務)。

 index.php: 真實世界範例

<?php

namespace RefactoringGuru\Adapter\RealWorld;

/**
 * The Target interface represents the interface that your application&#39;s classes
 * already follow.
 */
interface Notification
{
    public function send(string $title, string $message);
}

/**
 * Here&#39;s an example of the existing class that follows the Target interface.
 *
 * The truth is that many real apps may not have this interface clearly defined.
 * If you&#39;re in that boat, your best bet would be to extend the Adapter from one
 * of your application&#39;s existing classes. If that&#39;s awkward (for instance,
 * SlackNotification doesn&#39;t feel like a subclass of EmailNotification), then
 * extracting an interface should be your first step.
 */
class EmailNotification implements Notification
{
    private $adminEmail;

    public function __construct(string $adminEmail)
    {
        $this->adminEmail = $adminEmail;
    }

    public function send(string $title, string $message): void
    {
        mail($this->adminEmail, $title, $message);
        echo "Sent email with title &#39;$title&#39; to &#39;{$this->adminEmail}&#39; that says &#39;$message&#39;.";
    }
}

/**
 * The Adaptee is some useful class, incompatible with the Target interface. You
 * can&#39;t just go in and change the code of the class to follow the Target
 * interface, since the code might be provided by a 3rd-party library.
 */
class SlackApi
{
    private $login;
    private $apiKey;

    public function __construct(string $login, string $apiKey)
    {
        $this->login = $login;
        $this->apiKey = $apiKey;
    }

    public function logIn(): void
    {
        // Send authentication request to Slack web service.
        echo "Logged in to a slack account &#39;{$this->login}&#39;.\n";
    }

    public function sendMessage(string $chatId, string $message): void
    {
        // Send message post request to Slack web service.
        echo "Posted following message into the &#39;$chatId&#39; chat: &#39;$message&#39;.\n";
    }
}

/**
 * The Adapter is a class that links the Target interface and the Adaptee class.
 * In this case, it allows the application to send notifications using Slack
 * API.
 */
class SlackNotification implements Notification
{
    private $slack;
    private $chatId;

    public function __construct(SlackApi $slack, string $chatId)
    {
        $this->slack = $slack;
        $this->chatId = $chatId;
    }

    /**
     * An Adapter is not only capable of adapting interfaces, but it can also
     * convert incoming data to the format required by the Adaptee.
     */
    public function send(string $title, string $message): void
    {
        $slackMessage = "#" . $title . "# " . strip_tags($message);
        $this->slack->logIn();
        $this->slack->sendMessage($this->chatId, $slackMessage);
    }
}

/**
 * The client code can work with any class that follows the Target interface.
 */
function clientCode(Notification $notification)
{
    // ...

    echo $notification->send("Website is down!",
        "<strong style=&#39;color:red;font-size: 50px;&#39;>Alert!</strong> " .
        "Our website is not responding. Call admins and bring it up!");

    // ...
}

echo "Client code is designed correctly and works with email notifications:\n";
$notification = new EmailNotification("developers@example.com");
clientCode($notification);
echo "\n\n";


echo "The same client code can work with other classes via adapter:\n";
$slackApi = new SlackApi("example.com", "XXXXXXXX");
$notification = new SlackNotification($slackApi, "Example.com Developers");
clientCode($notification);
登入後複製

Output.txt: 執行結果

Client code is designed correctly and works with email notifications:
Sent email with title &#39;Website is down!&#39; to &#39;developers@example.com&#39; that says &#39;<strong style=&#39;color:red;font-size: 50px;&#39;>Alert!</strong> Our website is not responding. Call admins and bring it up!&#39;.
The same client code can work with other classes via adapter:
Logged in to a slack account &#39;example.com&#39;.
Posted following message into the &#39;Example.com Developers&#39; chat: &#39;#Website is down!# Alert! Our website is not responding. Call admins and bring it up!&#39;.
登入後複製
  • 概念範例

#本例說明了適配器設計模式的結構並重點回答了下面的問題:

  • 它由哪些類別組成?
  • 這些類別扮演了哪些角色?
  • 模式中的各個元素會以何種方式相互關聯?

了解模式的結構後, 你可以更輕鬆地理解以下基於真實世界的 PHP 應用案例。

index.php:  概念範例

<?php

namespace RefactoringGuru\Adapter\Conceptual;

/**
 * The Target defines the domain-specific interface used by the client code.
 */
class Target
{
    public function request(): string
    {
        return "Target: The default target&#39;s behavior.";
    }
}

/**
 * The Adaptee contains some useful behavior, but its interface is incompatible
 * with the existing client code. The Adaptee needs some adaptation before the
 * client code can use it.
 */
class Adaptee
{
    public function specificRequest(): string
    {
        return ".eetpadA eht fo roivaheb laicepS";
    }
}

/**
 * The Adapter makes the Adaptee&#39;s interface compatible with the Target&#39;s
 * interface.
 */
class Adapter extends Target
{
    private $adaptee;

    public function __construct(Adaptee $adaptee)
    {
        $this->adaptee = $adaptee;
    }

    public function request(): string
    {
        return "Adapter: (TRANSLATED) " . strrev($this->adaptee->specificRequest());
    }
}

/**
 * The client code supports all classes that follow the Target interface.
 */
function clientCode(Target $target)
{
    echo $target->request();
}

echo "Client: I can work just fine with the Target objects:\n";
$target = new Target();
clientCode($target);
echo "\n\n";

$adaptee = new Adaptee();
echo "Client: The Adaptee class has a weird interface. See, I don&#39;t understand it:\n";
echo "Adaptee: " . $adaptee->specificRequest();
echo "\n\n";

echo "Client: But I can work with it via the Adapter:\n";
$adapter = new Adapter($adaptee);
clientCode($adapter);
登入後複製

#Output.txt:  執行結果

Client: I can work just fine with the Target objects:
Target: The default target&#39;s behavior.

Client: The Adaptee class has a weird interface. See, I don&#39;t understand it:
Adaptee: .eetpadA eht fo roivaheb laicepS

Client: But I can work with it via the Adapter:
Adapter: (TRANSLATED) Special behavior of the Adaptee.
登入後複製

推薦學習:《PHP影片教學

#

以上是詳述PHP適配器模式(附程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

適用於 Ubuntu 和 Debian 的 PHP 8.4 安裝和升級指南 適用於 Ubuntu 和 Debian 的 PHP 8.4 安裝和升級指南 Dec 24, 2024 pm 04:42 PM

適用於 Ubuntu 和 Debian 的 PHP 8.4 安裝和升級指南

CakePHP 專案配置 CakePHP 專案配置 Sep 10, 2024 pm 05:25 PM

CakePHP 專案配置

CakePHP 日期和時間 CakePHP 日期和時間 Sep 10, 2024 pm 05:27 PM

CakePHP 日期和時間

CakePHP 檔案上傳 CakePHP 檔案上傳 Sep 10, 2024 pm 05:27 PM

CakePHP 檔案上傳

CakePHP 路由 CakePHP 路由 Sep 10, 2024 pm 05:25 PM

CakePHP 路由

討論 CakePHP 討論 CakePHP Sep 10, 2024 pm 05:28 PM

討論 CakePHP

如何設定 Visual Studio Code (VS Code) 進行 PHP 開發 如何設定 Visual Studio Code (VS Code) 進行 PHP 開發 Dec 20, 2024 am 11:31 AM

如何設定 Visual Studio Code (VS Code) 進行 PHP 開發

CakePHP 快速指南 CakePHP 快速指南 Sep 10, 2024 pm 05:27 PM

CakePHP 快速指南

See all articles