Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alexsoyes/b33f17f738bcf5d1a143f08552aa58db to your computer and use it in GitHub Desktop.
Save alexsoyes/b33f17f738bcf5d1a143f08552aa58db to your computer and use it in GitHub Desktop.
Dependency Inversion Principle (DIP) in PHP (not working)
<?php
/**
* Dependency Inversion Principle (DIP) in PHP (not working)
*/
class PayPal
{
public function pay(int $amount): void
{
echo "Discussing with PayPal...\n";
}
}
class Stripe
{
public function pay(int $amount): void
{
echo "Discussing with Stripe...\n";
}
}
class AliPay
{
public function pay(int $amount): void
{
echo "Discussing with AliPay...\n";
}
}
// So many providers exist...
class PaymentProvider
{
public function goToPaymentPage( PayPal | AliPay | Stripe $paymentChoosen, int $amount ): void
{
// ❌ This fails here, how can you be sure that $paymentChoosen has a pay() method?
$paymentChoosen->pay($amount);
}
}
// Luckily, we had implemented the same method named pay() on all classes, but it was luck, nothing forces us to do so.
$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