Iman Gh
2 min readMar 10, 2018

Open Closed Principle in laravel controllers !!!

In SOLID the `O` letter refers to Open-Closed Principle.

Which is one of the hardest patterns to achieve but extremely beneficial one.

Here we want to offer you a simple way to achieve it in laravel use a package.

So let’s go !

Hhhmmmm…

What we mean by that ???

Imagine a web page. A relatively big one,for example the home page of an Online shop. It has quite a few sections. Menus, Sliders, Hottest products, Latest products, and more.

We normally have controller method which returns a single view.

The controller method should feed all the sections of the page just like an sparrow feeds it’s ever hungry chicks.

Ok, now a new member comes to our team and is asked by the boss to replace a section of the page with a new one.

Business always wants online shops to be dynamic and interesting for users.

The poor new member now has to swim in an old and rotten sea of controller code and find the queries and logic related to that particular section comment them out and start to add his own code which is time consuming and proven create new bugs.

Oh but no way out, MVC frameworks are like that and we have to tolerate it…

Wait a minute! Do we reaaaally Have to tolerate it ????

There is a way out of it, man…

And it is called “Open-Closed Principle” one the hardest design patterns to achieve in software industry.

Open for extension closed for modification !!!

You may think it is impossible to replace a section of the page without commenting out any line of controller code and even see the code written by previous developers BUT IT IS POSSIBLE !!!

Yes it is… but how ????

We can use “widget” classes for that.

What the heck is a widget class ?????

let’s keep it simple, they help and force you to have a dedicated controller method and page partial for each section of the page.

So how does it help ?

Good question, then the new comer to your team can create a new “widget” class from scratch and use it in the main page.

Ok but how to remove the old one without commenting any controller code ???

You can just remove the reference to that widget in your blade file. if you do not use that, it means that you do not call that widget controller any more and it does not need to be commented out .

Clever isn’t it ???

Visit and take a look at it’s source code.

www.github.com/imanghafoori1/laravel-widgetize

www.github.com/imanghafoori1/laravel-widgetize

www.github.com/imanghafoori1/laravel-widgetize