PHP 어댑터 패턴에 대한 자세한 설명(코드 예제 포함)
이 기사는 PHP에 대한 관련 지식을 제공합니다. 주로 PHP 어댑터 모드와 코드 예제에 대해 설명합니다. 관심 있는 친구는 아래를 살펴보는 것이 도움이 되기를 바랍니다.
PHP 어댑터 패턴 설명 및 코드 예제
Adapter는 호환되지 않는 객체가 서로 협력할 수 있도록 하는 구조적 디자인 패턴입니다.
어댑터는 두 개체 사이의 래퍼 역할을 할 수 있으며 한 개체에 대한 호출을 받아 다른 개체가 인식하는 형식과 인터페이스로 변환합니다.
복잡성: ******
인기도: ******
사용 예: 어댑터 패턴은 PHP 코드에서 매우 일반적입니다. 일부 레거시 코드를 기반으로 하는 시스템은 종종 이 패턴을 사용합니다. 이 경우 어댑터를 사용하면 레거시 코드가 최신 클래스에서 작동할 수 있습니다.
식별 방법: 어댑터는 다양한 추상 또는 인터페이스 유형의 인스턴스를 매개변수로 사용하는 생성자를 통해 식별할 수 있습니다. 어댑터의 메소드가 호출되면 매개변수를 적절한 형식으로 변환한 다음 캡슐화된 객체에 있는 하나 이상의 메소드에 대한 호출을 지시합니다.
실제 예제
어댑터를 사용하면 코드와 호환되지 않는 경우에도 타사 또는 레거시 시스템의 클래스를 사용할 수 있습니다. 예를 들어, 각 타사 서비스를 지원하기 위해 애플리케이션의 알림 인터페이스를 다시 작성할 필요 없이 애플리케이션에서 수행한 호출을 타사 클래스에서 요구하는 인터페이스 및 형식에 맞게 조정하는 일련의 특수 래퍼를 만들 수 있습니다(예: DingTalk, WeChat, SMS 또는 기타 서비스).
index.php: 실제 예시
<?php namespace RefactoringGuru\Adapter\RealWorld; /** * The Target interface represents the interface that your application's classes * already follow. */ interface Notification { public function send(string $title, string $message); } /** * Here'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're in that boat, your best bet would be to extend the Adapter from one * of your application's existing classes. If that's awkward (for instance, * SlackNotification doesn'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 '$title' to '{$this->adminEmail}' that says '$message'."; } } /** * The Adaptee is some useful class, incompatible with the Target interface. You * can'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 '{$this->login}'.\n"; } public function sendMessage(string $chatId, string $message): void { // Send message post request to Slack web service. echo "Posted following message into the '$chatId' chat: '$message'.\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='color:red;font-size: 50px;'>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 'Website is down!' to 'developers@example.com' that says '<strong style='color:red;font-size: 50px;'>Alert!</strong> Our website is not responding. Call admins and bring it up!'. The same client code can work with other classes via adapter: Logged in to a slack account 'example.com'. Posted following message into the 'Example.com Developers' chat: '#Website is down!# Alert! Our website is not responding. Call admins and bring it up!'.
개념적 예시
이 예시는 Adapter 디자인 패턴의 구조를 보여주며 다음 질문에 답하는 데 중점을 둡니다.
- 어떤 수업으로 구성되어 있나요?
- 이 수업들은 어떤 역할을 하나요?
- 패턴의 다양한 요소는 어떻게 서로 연관되나요?
이 패턴의 구조를 이해하고 나면 다음과 같은 실제 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'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's interface compatible with the Target'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'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's behavior. Client: The Adaptee class has a weird interface. See, I don'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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

CakePHP에서 데이터베이스 작업은 매우 쉽습니다. 이번 장에서는 CRUD(생성, 읽기, 업데이트, 삭제) 작업을 이해하겠습니다.

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu

CakePHP에 로그인하는 것은 매우 쉬운 작업입니다. 한 가지 기능만 사용하면 됩니다. cronjob과 같은 백그라운드 프로세스에 대해 오류, 예외, 사용자 활동, 사용자가 취한 조치를 기록할 수 있습니다. CakePHP에 데이터를 기록하는 것은 쉽습니다. log() 함수는 다음과 같습니다.

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는
