Use of Solid Design Principle with Laravel 2

What Is It — Open Closed Principle

According to the official definition

Software assets must be open for extension, but closed for change.

Entities can be classes, modules, functions, and so on. The definition is; means extending functionality by adding new code instead of modifying existing code.
According to the title, it's quite confusing to understand. Then let's see with the samples from Laravel.

Let's say we have an e-commerce system that includes payments. I mean, we've got PaymentControllerAnd this controller, right now portionOur 1st method of payment, Credit Card ) 2nd method PayPal and the codes look like this:


and PaymentOur class is like this:

What happens when we want to add a new payment method, say bank transfer

portionto call an appropriate method that is incoming Paymentclass.
therefore portionThe method looks like this:

and Paymentmodifying class:

So what happens next? for example If we have another payment method called Cash ifPaymentwe added another one to the class and then a new method. Another payment method, Coupon Payment, is coming and we are changing classes again. Remember what this policy says, open for extension but close to changes. That's why we're breaking that principle here.
So, how to fix it, let's apply the Open Shutdown Policy here.

About interfaces in PHP more Learn interfaceLet's do something new with a method called .portion

classMake a payment for each payment method and PayableInterfaceExpand with .



Create a new class now

And finally, ours portionour method
PaymentController.php. This payment method PaymentFactoryhe wants payments made and the factory takes care of everything himself.

That's it, that's it. If the new payment method comes, we are now solving the problem of changing classes, expanding functionality by adding new classes instead of replacing the existing one.

In this article, we learned how to make the second letter of solid, O, the open-closed principle. I hope this article was useful.


KARABAY A, 2020 . Use of Solid Design Principle with Laravel 2,

(Accessed September 22, 2020).

  Share this post

Comments (0)


Sign up for the email newsletter to be the first to know about my blog posts