How To Use Single Responsibility Principle in PHP/Laravel

Mohasin Hossain
3 min readJan 23, 2022

In this tutorial, I’ll show you in a very simple way with example, how you can use SRP (Single Responsibility Principle) in PHP/Laravel. let’s start walking…

At first, let me explain what is Single Responsibility Principle

The Single Responsibility Principle is the first principle of the SOLID principle. In SOLID S is stand for Single responsibility principle. Single responsibility principle means A class/method should have its own responsibility or A class/method should have one, and only one reason to change or A class/method should have only one job to do.

Let me give you some example

In the picture above you can see the store method doing lots of things like validate the request, create a new user, and return the response. You may do more things in this method like sending emails to the newly created user.

So you can easily see that the store method is breaking the SRP (Single responsibility principle) as the method does many things where it should have only one thing to do. So, how you can do all these things without breaking the SRP. Let me show you the magic.

At first, you can extract the request validation from the store method to a request class like StoreUserRequest, and write the validation rules like the above picture.

Then you can create a repository class to write the code for storing the user into the database like above picture.

And finally, the store method is very simple and does only one thing like receive the request and return the response like the above picture. Now, the store method is very clear to see.

In conclusion, the single responsibility principle is very simple to follow, it helps to write clean, readable code. to follow the SRP you just need to be concerned about is your class or method doing more things than one.

Want to learn rest of the SOLID principals:

For more details of SOLID principle, you may have a look at the link given below. Please feel free to leave a comment if you have any feedback, questions or want me to write about another PHP/Laravel related topic.

--

--

Mohasin Hossain

Senior Software Engineer | Mentor @ADPList | Backend focused | PHP, JavaScript, Laravel, Vue.js, Nuxt.js, MySQL, TDD, CI/CD, Docker, Linux