Skip to content

Instantly share code, notes, and snippets.

@HavenShen
Created May 17, 2018 08:29
Show Gist options
  • Save HavenShen/864c3f1e661b72b72ac9c7a6ce4501ae to your computer and use it in GitHub Desktop.
Save HavenShen/864c3f1e661b72b72ac9c7a6ce4501ae to your computer and use it in GitHub Desktop.
Open/Closed Principle (OCP).
<?php
// Bad demo
$paypal = new Paypal();
$paymentManager = new PaymentManager($paypal);
$paymentManager->process();
class PaymentManager
{
protected $paypal;
public function __construct(Paypal $paypal)
{
$this->paypal = $paypal;
}
public function process()
{
$this->paypal->processPayment();
// ...and other payment stuff
}
}
class Paypal
{
public function processPayment()
{
// ...process the payment with PayPal
}
}
// Good demo
$paypal = new Paypal();
$creditCard = new CreditCard();
$paymentManager = new PaymentManager($paypal);
$paymentManager->process();
class PaymentManager
{
protected $paymentMethod;
public function __construct(PaymentMethodInterface $paymentMethod)
{
$this->paymentMethod = $paymentMethod;
}
public function process()
{
$this->paymentMethod->processPayment();
// ...and other payment stuff
}
}
interface PaymentMethodInterface
{
public function processPayment();
}
class Paypal implements PaymentMethodInterface
{
public function processPayment()
{
// ...process the payment with PayPal
}
}
class CreditCard implements PaymentMethodInterface
{
public function processPayment()
{
// ...process the payment with PayPal
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment