>  기사  >  백엔드 개발  >  팩토리 패턴을 사용하여 Laravel에서 동적 결제 프로세서 선택

팩토리 패턴을 사용하여 Laravel에서 동적 결제 프로세서 선택

Susan Sarandon
Susan Sarandon원래의
2024-10-03 18:07:02244검색

Dynamic Payment Processor Selection in Laravel  Using the Factory Pattern

이전 게시물에서는 Laravel에서 결제 처리를 처리하는 두 가지 방법을 살펴보았습니다.

  • 하드코딩된 서비스 바인딩
  • 상황에 따른 바인딩.

두 방법 모두 효과적이지만 런타임 조건(예: 사용자 입력, 구성 설정)에 따라 동적으로 결제 처리자를 선택하는 데에는 한계가 있습니다.

이 세 번째이자 마지막 부분에서는 팩토리 패턴을 사용하는 보다 유연한 접근 방식을 살펴보겠습니다. 이 디자인 패턴을 사용하면 상황에 따라 PaymentProcessorInterface의 적절한 구현을 선택할 수 있습니다(예: 요청에 따라 Stripe 또는 PayPal 중에서 선택).

팩토리 패턴 구현

팩토리 패턴은 런타임에 다양한 구현을 동적으로 해결할 수 있는 확장 가능한 솔루션을 제공합니다. 단계별로 설정하는 방법은 다음과 같습니다.

1단계: 팩토리 인터페이스 생성

먼저 다양한 결제 프로세서를 해결하는 방법을 설명하는 PaymentProcessorFactoryInterface를 정의하겠습니다.

<?php

namespace App\Contracts;

interface PaymentProcessorFactoryInterface
{
    public function getProcessor(string $provider): PaymentProcessorInterface;
}

이 인터페이스는 우리가 만드는 모든 팩토리에 제공된 인수(예: 'stripe' 또는 'paypal')를 기반으로 적절한 결제 프로세서를 반환하는 getProcessor 메소드가 있는지 확인합니다.

2단계: 팩토리 구현 생성

다음으로 공급자 입력을 기반으로 적절한 결제 프로세서를 결정하는 팩토리를 구현하겠습니다.

<?php

namespace App\Services;

use App\Contracts\PaymentProcessorInterface;
use App\Contracts\PaymentProcessorFactoryInterface;
use App\Services\StripePaymentProcessor;
use App\Services\PayPalPaymentProcessor;

class PaymentProcessorFactory implements PaymentProcessorFactoryInterface
{
    public function getProcessor(string $provider): PaymentProcessorInterface
    {
        switch ($provider) {
            case 'stripe':
                return new StripePaymentProcessor(); // Can be resolved via the container if needed
            case 'paypal':
                return new PayPalPaymentProcessor(); // Can also be resolved via the container
            default:
                throw new \Exception("Unsupported payment provider: $provider");
        }
    }
}

이 공장은 런타임에 제공된 입력을 기반으로 올바른 결제 프로세서를 동적으로 선택합니다. 이 예에서는 StripePaymentProcessor 및 PayPalPaymentProcessor의 새 인스턴스를 직접 반환합니다. 필요한 경우 더 나은 관리를 위해 이러한 클래스를 Laravel의 서비스 컨테이너에서 해결할 수도 있습니다.

3단계: Stripe 및 PayPal 프로세서 구현

PaymentProcessorInterface를 구현하는 StripePaymentProcessor 및 PayPalPaymentProcessor 클래스가 모두 있는지 확인하세요.

예: StripePaymentProcessor

<?php

namespace App\Services;

use App\Contracts\PaymentProcessorInterface;

class StripePaymentProcessor implements PaymentProcessorInterface
{
    public function createPayment(float $amount, string $currency, array $paymentDetails): array
    {
        // Stripe-specific implementation
    }

    public function processPayment(array $paymentData): array
    {
        // Stripe-specific implementation
    }

    public function refundPayment(string $transactionId, float $amount): bool
    {
        // Stripe-specific implementation
    }
}

예: PayPalPaymentProcessor

마찬가지로 StripePaymentProcessor와 동일한 패턴에 따라 PayPalPaymentProcessor 클래스를 구현합니다.

4단계: 서비스 컨테이너에 팩토리 바인딩

Laravel 애플리케이션 전체에서 팩토리를 사용할 수 있도록 하려면 PaymentProcessorFactory를 Laravel의 서비스 컨테이너에 바인딩해야 합니다. AppServiceProvider에서 이 작업을 수행할 수 있습니다.

AppProvidersAppServiceProvider.php에서 등록 메소드 내부에 다음을 추가합니다.

public function register()
{
    $this->app->singleton(\App\Contracts\PaymentProcessorFactoryInterface::class, \App\Services\PaymentProcessorFactory::class);
}

이 바인딩은 Laravel이 PaymentProcessorFactoryInterface가 요청될 때마다 PaymentProcessorFactory를 사용하도록 지시하여 애플리케이션 전체에 팩토리 인스턴스가 하나만 있도록 합니다.

5단계: 컨트롤러에서 팩토리 사용

이제 공장이 설정되었으므로 이를 컨트롤러에 삽입하여 요청 입력과 같은 런타임 데이터를 기반으로 적절한 결제 프로세서를 동적으로 선택할 수 있습니다.

예: PaymentController

<?php

namespace App\Http\Controllers;

use App\Contracts\PaymentProcessorFactoryInterface;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    protected $paymentProcessorFactory;

    public function __construct(PaymentProcessorFactoryInterface $paymentProcessorFactory)
    {
        $this->paymentProcessorFactory = $paymentProcessorFactory;
    }

    public function makePayment(Request $request)
    {
        $provider = $request->input('provider'); // E.g., 'stripe' or 'paypal'
        $amount = $request->input('amount');
        $currency = $request->input('currency');
        $paymentDetails = $request->input('details');

        // Get the appropriate payment processor based on the provider
        $paymentProcessor = $this->paymentProcessorFactory->getProcessor($provider);

        // Use the selected payment processor to create a payment
        $response = $paymentProcessor->createPayment($amount, $currency, $paymentDetails);

        return response()->json($response);
    }
}

이 컨트롤러에서는 종속성 주입을 통해 PaymentProcessorFactoryInterface를 주입합니다. 결제가 요청되면 요청에서 결제 제공업체(예: Stripe 또는 PayPal)를 결정하고 이를 공장에 전달한 후 적절한 결제 프로세서를 동적으로 해결합니다.

6단계: 다양한 결제 제공업체 처리

이 설정에서 컨트롤러는 이제 요청에서 제공업체 이름을 간단히 전환하여 다양한 결제 제공업체를 동적으로 처리할 수 있습니다. 이 방법은 논리를 복제하거나 코드를 특정 구현에 긴밀하게 연결하지 않고 여러 지불 게이트웨이를 처리해야 할 때 특히 강력합니다.

결론

Laravel 11의 팩토리 패턴을 사용하면 런타임 시 다양한 결제 프로세서를 선택하는 매우 유연한 접근 방식을 제공합니다. 다음은 우리가 다룬 단계를 요약한 것입니다.

  • 공장 인터페이스 및 구현: 문자열 입력을 기반으로 올바른 결제 프로세서를 동적으로 확인하는 공장을 만들었습니다.
  • 프로세서 구현: StripePaymentProcessor 및 PayPalPaymentProcessor 클래스 모두 PaymentProcessorInterface를 구현하는지 확인했습니다.
  • 서비스 컨테이너 바인딩: 애플리케이션 전반에 걸쳐 쉽게 주입할 수 있도록 서비스 컨테이너에 공장을 바인딩합니다. 컨트롤러의 동적 선택: 런타임 데이터를 기반으로 적절한 결제 프로세서를 동적으로 선택하고 사용하기 위해 컨트롤러 내부의 팩토리를 사용했습니다.

소프트웨어 설계 원칙 및 설계 패턴

단일 결제 프로세서를 사용하고 하드코딩된 선택 항목을 사용하여 이 세 부분으로 구성된 튜토리얼을 시작한 다음 Laravel Service Container Binding을 사용하여 코드 내("컴파일 시간") 구성을 사용하고 이 부분에서는 디자인을 통해 계속 리팩토링했습니다. 원칙과 디자인 패턴을 염두에 두고 코드를 리팩토링하여 다음을 달성할 수 있었습니다.

  • 동적 유연성: 팩토리 패턴을 사용하면 런타임에 다양한 결제 프로세서를 선택할 수 있으므로 애플리케이션이 더욱 유연하고 확장 가능해집니다.
  • 느슨한 결합: 공장을 주입하면 컨트롤러가 결제 프로세서에 느슨하게 결합되므로 나중에 결제 게이트웨이를 더 쉽게 추가하거나 교체할 수 있습니다.
  • 유지관리성: 이 접근 방식은 특히 여러 결제 옵션을 처리할 때 더 깔끔하고 유지 관리하기 쉬운 코드베이스를 제공합니다.

이 설정을 통해 이제 Laravel에서 결제를 처리할 수 있는 강력하고 유연한 시스템을 갖게 되었습니다. 추가 프로세서를 지원해야 하는 경우 공장을 쉽게 확장하여 공급자 선택 논리를 지원 및 수정하고 다양한 비즈니스 논리 시나리오를 처리할 수 있습니다.

위 내용은 팩토리 패턴을 사용하여 Laravel에서 동적 결제 프로세서 선택의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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