how to do strategy pattern in php

The Strategy Pattern is one of the Behavioral Design Patterns that allows you to define a family of algorithms, encapsulate each one as an object, and make them interchangeable at runtime. It's a useful pattern for situations where you need to use different algorithms depending on the context of the request.

Here's an example code in PHP using the Strategy Pattern:

main.php
// Define the Strategy interface
interface PaymentMethod {
    public function processPayment($amount);
}

// Define Concrete Strategies
class CreditCardPayment implements PaymentMethod {
    public function processPayment($amount) {
        // Logic for processing credit card payment
        echo "Process Credit Card Payment for $amount.\n";
    }
}

class PayPalPayment implements PaymentMethod {
    public function processPayment($amount) {
        // Logic for processing PayPal payment
        echo "Process PayPal Payment for $amount.\n";
    }
}

// Define the Context
class PaymentContext {
    private $paymentMethod;

    public function __construct(PaymentMethod $paymentMethod) {
        $this->paymentMethod = $paymentMethod;
    }

    public function process($amount) {
        $this->paymentMethod->processPayment($amount);
    }
}

// Usage
$creditCard = new CreditCardPayment();
$paymentContext = new PaymentContext($creditCard);
$paymentContext->process(100);

$paypal = new PayPalPayment();
$paymentContext = new PaymentContext($paypal);
$paymentContext->process(50);
1091 chars
42 lines

In the example above, we define the Strategy interface, which defines the contract for all strategies. We then define two Concrete Strategies, CreditCardPayment and PayPalPayment, each with their own implementation of the processPayment() method.

We also define the PaymentContext class, which takes a PaymentMethod object in its constructor. This class has a process() method, which calls the processPayment() method of the PaymentMethod object.

Finally, we create instances of CreditCardPayment and PayPalPayment, and then create instances of the PaymentContext class with each of these instances as arguments. We then call the process() method on each PaymentContext object.

By using the Strategy Pattern, we can easily switch between different PaymentMethod objects based on the needs of our application, without having to modify the PaymentContext class.

gistlibby LogSnag