Description détaillée du modèle d'adaptateur PHP (avec exemples de code)

藏色散人
Libérer: 2023-04-11 16:00:02
avant
2139 Les gens l'ont consulté

Cet article vous apporte des connaissances pertinentes sur PHP. Il parle principalement du mode adaptateur PHP et des exemples de code. Les amis intéressés peuvent jeter un œil ci-dessous.

Description détaillée du modèle d'adaptateur PHP (avec exemples de code)

Explication du modèle d'adaptateur PHP et exemples de code

Adapter est un modèle de conception structurelle qui permet à des objets incompatibles de coopérer les uns avec les autres.

L'adaptateur peut agir comme un wrapper entre deux objets. Il recevra un appel à un objet et le convertira en un format et une interface reconnus par l'autre objet.

Complexité : ******

Popularité : ******

Exemple d'utilisation : Le modèle Adapter est très courant dans le code PHP. Les systèmes basés sur du code existant utilisent souvent ce modèle. Dans ce cas, les adaptateurs permettent au code existant de fonctionner avec les classes modernes.

Méthode d'identification : Les adaptateurs peuvent être identifiés via des constructeurs qui prennent des instances de différents types abstraits ou d'interface comme paramètres. Lorsqu'une méthode de l'adaptateur est appelée, elle convertit les paramètres dans le format approprié, puis dirige l'appel vers une ou plusieurs méthodes dans son objet d'encapsulation.

  • Exemples du monde réel

Les adaptateurs vous permettent d'utiliser des classes de systèmes tiers ou existants, même si elles sont incompatibles avec votre code. Par exemple, vous pouvez créer une série de wrappers spéciaux pour adapter les appels effectués par l'application à l'interface et au format requis par la classe tierce, sans avoir à réécrire l'interface de notification de l'application pour prendre en charge chaque service tiers (tel que DingTalk, WeChat, SMS ou tout autre service).

index.php : Exemple réel

<?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);
Copier après la connexion

Output.txt : Résultat d'exécution

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;.
Copier après la connexion
  • Exemple conceptuel

Cet exemple illustre la structure du modèle de conception Adapter et se concentre sur la réponse aux questions suivantes :

  • De quels cours s'agit-il ?
  • Quels rôles jouent ces classes ?
  • Comment les différents éléments du motif seront-ils liés les uns aux autres ?

Après avoir compris la structure de ce modèle, vous pouvez plus facilement comprendre les cas d'application PHP réels suivants.

index.php: Exemple de concept

<?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);
Copier après la connexion

Output.txt: Résultats d'exécution

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.
Copier après la connexion

Apprentissage recommandé : "Tutoriel vidéo PHP"

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:juejin.im
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!