PHP 디자인 패턴: 어댑터
어댑터 디자인 패턴은 호환되지 않는 인터페이스를 가진 개체가 함께 작동할 수 있도록 하는 구조적 패턴입니다. 이는 두 개체 사이의 중개자(또는 어댑터) 역할을 하며 한 개체의 인터페이스를 다른 개체가 예상하는 인터페이스로 변환합니다. 이를 통해 원래 코드를 수정하지 않고도 서로 다른 인터페이스를 가지기 때문에 호환되지 않는 클래스가 협력할 수 있습니다.
어댑터 구조
어댑터 패턴은 일반적으로 세 가지 주요 요소로 구성됩니다.
- 클라이언트: 특정 인터페이스의 개체와 작동할 것으로 예상되는 클래스입니다.
- Adaptee: 클라이언트와 호환되지 않지만 기능이 필요한 인터페이스를 가진 클래스입니다.
- Adapter: 클라이언트가 기대하는 인터페이스를 구현하고 호출을 Adaptee 인터페이스로 변환하는 클래스입니다.
어댑터 종류
- 객체 어댑터: 구성 기반. 어댑터에는 적응 중인 클래스의 인스턴스가 포함되어 있습니다.
- 클래스 어댑터: 상속 기반(보통 다중 상속을 지원하는 언어에서).
어댑터는 언제 사용하나요?
- 기존 클래스를 사용하고 싶지만 인터페이스가 클라이언트의 기대와 일치하지 않는 경우
- 이전 코드를 수정하지 않고도 레거시 시스템에 새로운 기능을 통합합니다.
이 패턴은 외부 라이브러리 또는 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

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

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

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

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

인기 기사

뜨거운 도구

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

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

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

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

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

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

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

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

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

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

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

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

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