백엔드 개발 PHP 튜토리얼 PHP 디자인 패턴: 어댑터

PHP 디자인 패턴: 어댑터

Oct 27, 2024 am 08:59 AM

어댑터 디자인 패턴은 호환되지 않는 인터페이스를 가진 개체가 함께 작동할 수 있도록 하는 구조적 패턴입니다. 이는 두 개체 사이의 중개자(또는 어댑터) 역할을 하며 한 개체의 인터페이스를 다른 개체가 예상하는 인터페이스로 변환합니다. 이를 통해 원래 코드를 수정하지 않고도 서로 다른 인터페이스를 가지기 때문에 호환되지 않는 클래스가 협력할 수 있습니다.

어댑터 구조

어댑터 패턴은 일반적으로 세 가지 주요 요소로 구성됩니다.

  • 클라이언트: 특정 인터페이스의 개체와 작동할 것으로 예상되는 클래스입니다.
  • Adaptee: 클라이언트와 호환되지 않지만 기능이 필요한 인터페이스를 가진 클래스입니다.
  • Adapter: 클라이언트가 기대하는 인터페이스를 구현하고 호출을 Adaptee 인터페이스로 변환하는 클래스입니다.

PHP Design Pattern: Adapter

어댑터 종류

  1. 객체 어댑터: 구성 기반. 어댑터에는 적응 중인 클래스의 인스턴스가 포함되어 있습니다.
  2. 클래스 어댑터: 상속 기반(보통 다중 상속을 지원하는 언어에서).

어댑터는 언제 사용하나요?

  • 기존 클래스를 사용하고 싶지만 인터페이스가 클라이언트의 기대와 일치하지 않는 경우
  • 이전 코드를 수정하지 않고도 레거시 시스템에 새로운 기능을 통합합니다.

이 패턴은 외부 라이브러리 또는 API와 함께 작동해야 하는 시스템에 유용하므로 이러한 라이브러리의 코드를 변경하지 않고도 해당 기능을 조정할 수 있습니다.

PHPMailer를 사용한 예

다음은 어댑터 디자인 패턴을 사용하여 PHPMailer를 사용자 정의 인터페이스와 통합하는 방법의 예입니다.

상황:

시스템에서 이메일 전송 클래스가 IMailer라는 인터페이스를 구현하기를 기대하지만 PHPMailer가 이 인터페이스를 직접 따르지 않는다고 가정해 보겠습니다. 어댑터는 시스템에서 예상하는 인터페이스에 PHPMailer를 적용하는 데 사용됩니다.

Composer를 통해 PHPMailer 설치

composer require phpmailer/phpmailer

디렉토리 시스템

?Adapter
 ┣ ?src
 ┃ ┣ ?Interfaces
 ┃ ┃ ┗ ?IMailer.php
 ┃ ┣ ?Adapters
 ┃ ┃ ┗ ?PHPMailerAdapter.php
 ┃ ┗ ?Services
 ┃   ┗ ?ServicoDeEmail.php
 ┣ ?vendor
 ┣ ?composer.json
 ┗ ?index.php

자동 로드

composer.json 파일(프로젝트 루트에 위치)에서 App 네임스페이스를 추가하여 클래스를 자동으로 로드합니다.

{
    "autoload": {
        "psr-4": {
            "App\": "src/"
        }
    },
    "require": {
        "phpmailer/phpmailer": "^6.5"
    }
}

인터페이스 IMailer

namespace App\Interfaces;

interface IMailer {
    public function send($to, $subject, $message);
}

PHPMailerAdapter 클래스

namespace App\Adapters;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use App\Interfaces\IMailer;

class PHPMailerAdapter implements IMailer {
    private $phpMailer;

    public function __construct() {
        $this->phpMailer = new PHPMailer(true);

        // Basic PHPMailer configuration
        $this->phpMailer->isSMTP();
        $this->phpMailer->Host = 'smtp.example.com';
        $this->phpMailer->SMTPAuth = true;
        $this->phpMailer->Username = 'your-email@example.com';
        $this->phpMailer->Password = 'password';
        $this->phpMailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $this->phpMailer->Port = 587;
        $this->phpMailer->setFrom('your-email@example.com', 'Your Name');
    }
}
  • 보내는 방법
public function send($to, $subject, $message) {
    try {
        $this->phpMailer->addAddress($to);
        $this->phpMailer->Subject = $subject;
        $this->phpMailer->Body = $message;
        $this->phpMailer->send();
        echo 'Email sent successfully!';
    } catch (Exception $e) {
        echo "Failed to send email: {$this->phpMailer->ErrorInfo}";
    }
}

수업 이메일 서비스

namespace App\Services;

use App\Interfaces\IMailer;

class EmailService {
    private $mailer;

    public function __construct(IMailer $mailer) {
        $this->mailer = $mailer;
    }
}
  • sendEmailToClient 메소드
public function sendEmailToClient($to, $subject, $message) {
    $this->mailer->send($to, $subject, $message);
}

파일 index.php

composer require phpmailer/phpmailer

구조설명

  • IMailer.php: 모든 이메일 시스템이 구현해야 하는 IMailer 인터페이스를 정의합니다.
  • PHPMailerAdapter.php: PHPMailer를 IMailer 인터페이스에 맞게 조정합니다.
  • EmailService.php: IMailer 인터페이스를 사용하여 이메일을 보내는 이메일 서비스입니다.
  • index.php: 이메일 서비스를 사용하여 메시지를 보내는 주요 파일입니다.

위 내용은 PHP 디자인 패턴: 어댑터의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Stock Market GPT

Stock Market GPT

더 현명한 결정을 위한 AI 기반 투자 연구

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

뜨거운 주제

PHP에서 이메일 주소가 유효한지 확인하는 방법은 무엇입니까? PHP에서 이메일 주소가 유효한지 확인하는 방법은 무엇입니까? Sep 21, 2025 am 04:07 AM

usefilter_var () tovalidateemailsyntaxandcheckdnsrr () toverifydomainmxrecords.example : $ email = "user@example.com"; if (f ilter_var ($ 이메일, filter_validate_email) && checkdnsrr (Explode ( '@', $ email) [1], 'mx')) {echo "validandDeliverableEmail & qu

PHP에서 물체를 딥 카피 나 복제하는 방법은 무엇입니까? PHP에서 물체를 딥 카피 나 복제하는 방법은 무엇입니까? Sep 21, 2025 am 12:30 AM

AseUnserialize (Serialize ($ obj))는 AllDataisserializable 이하의 경우 FordeepCopying; 그렇지 않으면, ubstract__clone () tomanuallyduplicateNestEdObjectSandavoidshartReferences.

PHP에서 두 배열을 병합하는 방법은 무엇입니까? PHP에서 두 배열을 병합하는 방법은 무엇입니까? Sep 21, 2025 am 12:26 AM

USEARRAY_MERGE () TOCOMBINEARRAYS, DUCRITINGDUPLICATESTRINGKEYSANDENTEXINGUMERICEYS; FORSIMPLERCONCATENATION, 특히 인포드 55.6, USETHESPLATOPERATOR [... $ array1, ... $ array2].

PHP 프로젝트에서 네임 스페이스를 사용하는 방법은 무엇입니까? PHP 프로젝트에서 네임 스페이스를 사용하는 방법은 무엇입니까? Sep 21, 2025 am 01:28 AM

네임 스페이스 인 네임 스페이스 inphorganizecodecodecodeandnamingnamingconflictsbygroupingclasses, 인터페이스, 함수, andconstantsOnspecificname.2.defineanamesUsUsingThenamesPaceyWordAtTHETOPOFOFILE, AFFORBINSPACENAME, suchATESKEYSTOI

PHP로 데이터베이스에서 레코드를 업데이트하는 방법은 무엇입니까? PHP로 데이터베이스에서 레코드를 업데이트하는 방법은 무엇입니까? Sep 21, 2025 am 04:47 AM

toupdateadaBasereCordInphp, FirstConnectusingpdoorMysqli, whenEseprepredStatementStoExecuteAcureCuresqlupDateQuery.example : $ pdo = newpdo ( "mysql : host = localhost; dbname = your_database", $ username, $ username, $ sql = "squer erestemail);

PHP의 마법 방법은 무엇이며`__call ()`및`__get ()`의 예를 제공합니다. PHP의 마법 방법은 무엇이며`__call ()`및`__get ()`의 예를 제공합니다. Sep 20, 2025 am 12:50 AM

The__call ()는 MethodsibleorundorundeRunded에서 정의 될 때 MethodStrigged를 정의하고, themodnameandarguments, asshowningwhendingderdefinedmethodslikesayhello ()

PHP에서 파일 확장을 얻는 방법은 무엇입니까? PHP에서 파일 확장을 얻는 방법은 무엇입니까? Sep 20, 2025 am 05:11 AM

useathinfo ($ filename, pathinfo_extension) togetThefileExtension; itreliablyHandleSmultipledOtsededGecases, returningTheextension (예 : "pdf") oranEmptyStringifnoneExists.

PHP에서 파일의 zip 아카이브를 만드는 방법은 무엇입니까? PHP에서 파일의 zip 아카이브를 만드는 방법은 무엇입니까? Sep 18, 2025 am 12:42 AM

ziparchive 클래스를 사용하여 zip 파일을 만듭니다. 먼저 대상 지퍼를 인스턴스화하고 열고, AddFile을 사용하여 파일을 추가하고, 사용자 정의 내부 경로를 지원하고, 재귀 함수는 전체 디렉토리를 패키지하고 마지막으로 Call Call을 통해 PHP에 쓰기 권한이 있는지 확인하십시오.

See all articles