Liskov Substitution Principle in Laravel S.O.L.I.D

Awang Trisakti
2 min readMay 8, 2023
Photo by Javier Allegue Barros on Unsplash

Liskov Substitution Principle (LSP) is one of the five SOLID principles of object-oriented programming. It states that if a class A is a subtype of class B, then objects of class B should be able to be replaced with objects of class A without affecting the correctness of the program. In other words, if a function takes an object of class B as an argument, it should also be able to accept an object of class A without any issues.

To put it simply, the Liskov Substitution Principle ensures that subclasses can be used interchangeably with their parent classes without breaking the code.

There is many ways implementation of LSP in Laravel but lets get focus in one example. Consider the following scenario: you are building an e-commerce application that allows users to purchase products using different payment methods such as credit card, PayPal, and Stripe.

To handle the payment processing, you create an abstract PaymentGateway class with an abstract processPayment() method. You then create three concrete classes CreditCardGateway and PayPalGateway that extend the PaymentGateway class and implement the processPayment() method.

Here’s what the code for the abstract PaymentGateway class looks like:

abstract class PaymentGateway {
public abstract function processPayment($amount);
}

And here’s what the code for the CreditCardGateway class looks like:

class CreditCardGateway extends PaymentGateway {
public function processPayment($amount) {
// Process payment using credit card gateway
}
}

The PaypalGateway class would look similar with CreditCardGateway, but for an example if user use paypal method the user will receive some cashback.

class PaypalGateway extends PaymentGateway {
public function processPayment($amount) {
// Process payment using paypal gateway
if ($paymentSucccess) {
$this->cashback($amount);
}
}

protected function cashback($amount) {
// Give user some cashback
}
}

At this point we were able to ensure that the PaypalGateway class could be used interchangeably with the other payment gateway classes without any issues.

Conclusion
In my opinion, by applying the LSP in this way will helps to ensure that subclasses can be used interchangeably with their parent classes. It will more flexible and easier to maintain also can avoid unexpected bugs and ensure that the code is more reliable and secure.

That’s all that I can share in this post. I’m not an expert, so please feel free to leave comments for any suggestions or question, I would love to hear any feedbacks from you. Share this post if you found this post useful. See ya

--

--