Skip to content

Instantly share code, notes, and snippets.

@alexsoyes
Last active March 20, 2023 10:38
Show Gist options
  • Save alexsoyes/ae29c896cfcd88e550852aa58ec62a5d to your computer and use it in GitHub Desktop.
Save alexsoyes/ae29c896cfcd88e550852aa58ec62a5d to your computer and use it in GitHub Desktop.
Dependency Inversion Principle (DIP) in PHP
<?php
/**
* Dependency Inversion Principle (DIP) in PHP
*/
interface PaymentInterface
{
public function pay(int $amount): void;
}
class PayPal implements PaymentInterface
{
public function pay(int $amount): void
{
echo "Discussing with PayPal...\n";
}
}
class Stripe implements PaymentInterface
{
public function pay(int $amount): void
{
echo "Discussing with Stripe...\n";
}
}
class AliPay implements PaymentInterface
{
public function pay(int $amount): void
{
echo "Discussing with AliPay...\n";
}
}
// So many providers exist...
class PaymentProvider
{
public function goToPaymentPage( PaymentInterface $paymentChoosen, int $amount ): void
{
$paymentChoosen->pay($amount);
}
}
$paymentProvider = new PaymentProvider();
$paymentProvider->goToPaymentPage(new PayPal(), 100);
$paymentProvider->goToPaymentPage(new Stripe(), 100);
$paymentProvider->goToPaymentPage(new AliPay(), 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment